C++ の WebAssembly 入門

関連リソース

WebAssembly で使用されるヘルプ ドキュメント

奉納する

ダウンロードとインストール

# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git

# Enter that directory
cd emsdk

# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull

# Download and install the latest SDK tools. 可能需要代理才能下载,有时候多弄几次也行。
./emsdk install latest  

# Make the "latest" SDK "active" for the current user. (writes .emscripten file)
./emsdk activate latest

# Activate PATH and other environment variables in the current terminal
# Windows 下运行emsdk_env.bat   如果没有在环境变量里面设置,那么每次启动的时候都需要调用这个。
emsdk_env.bat

cmake インストール

インターネット上の一般的な例は、すべて直接 em++ で行われています. この方法は、開始するためのテスト例を記述するためにのみ使用され、代表的なものではありません.

mingw-64のインストール

WebAssembly のコンパイルに使用する C++ プログラムは、インターネット上の nmake でコンパイルすることもできますが、やはり WebAssembly は Linux 環境に似ており、mingw-64 を使用してコンパイルする方が信頼性が高くなります (コード内の Windows コードの場合)。

上記の 2 つの環境をインストールする最も簡単な方法は、qt プログラムをインストールし、内部でカスタム インストールを選択し、cmake と mingw64 のバージョンを確認し、インストールの完了後に関連するパスを環境変数に取得することです。私がインストールしたqt6.2バージョンなど

画像.png

C++ の例

  1. cmake プロジェクト ファイルの書き込み
cmake_minimum_required(VERSION 3.4.1)

project(example CXX)

set(lib_name "example")

add_executable(${lib_name} main.cpp)

target_link_libraries(${lib_name})
# EXIT_RUNTIME=1 表示运行完main函数需要退出运行时。类似于em++ 编译时需要指定的参数
set_target_properties(${lib_name} PROPERTIES LINK_FLAGS "-s EXIT_RUNTIME=1")
#include <stdio.h>
#include <emscripten.h>
int main(int argc, char *argv[])
{
    
    
	printf("hello world");
	return 0;
}

生成コンパイル

#启动cmd 执行emsdk中的emsdk_env.bat之后,切换到当前CMakeLists.txt 
mkdir em
cd em 
emcmake cmake ..
emmake make 

画像.png
生成ディレクトリに example.js および example.wasm ファイルが生成されます。

htmlファイルを書く

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<canvas id=foo width=300 height=300></canvas>
//引用刚才生成的example.js文件
<script src="example.js"></script>
<script>
  Module.onRuntimeInitialized = function() {
      
      
    //调用c++封装的函数,main函数会在加载的时候自动运行。如果在这个里面再次调用,会出现调用两次
    Module._main();
  }
</script>
<body>
   <p>this is a example</p>
</body>
</html>

実行開始

## 不能直接打开index.html
emrun --no_browser --port 8080 .

ブラウザーに 127.0.0.1:8080 と入力し、F12 を押して、開発者のデバッグを開きます。
画像.png

おすすめ

転載: blog.csdn.net/qq_33377547/article/details/124770415