一、windows環境搭建
先安裝cmake、git,然後:
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
git pull
emsdk install latest
emsdk activate latest
emsdk_env.bat
#emsdk update #更新指令,備用
二、最簡helloworld
mkdir hello
cd hello
建立hello.c:
#include <stdio.h>
int main(int argc, char ** argv) {
printf("Hello, world!\n");
}
編譯運作:
emcc hello.c -s WASM=1 -o hello.html
emrun --no_browser --port 8080 .
用浏覽器打開:http://localhost:8080/hello.html
三、使用JavaScrip調用WebAssembly函數
hello.c:
#include <stdio.h>
#include <emscripten/emscripten.h>
int main(int argc, char ** argv) {
printf("Hello World\n");
}
#ifdef __cplusplus
extern "C" {
#endif
int EMSCRIPTEN_KEEPALIVE myFunction(int argc, char ** argv) {
printf("我的函數已被調用\n");
}
#ifdef __cplusplus
}
#endif
編譯:
emcc hello.c -s WASM=1 -o hello.html -s "EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']"
編譯參數: -s "EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" 表示導出ccall和cwrap兩個函數
運作後在console中手動調用 Module.ccall('myFunction', null, null, null)
Module.ccall中的4個參數分别指:C函數名,傳回類型,參數類型(數組)和參數(也是數組)。
例如,如果函數接受2個字元串作為參數,我們需要通過這樣調用它:
Module.ccall('hello','number',['string','string'],['hello','world'])
可以使用的類型有null,string,number,array和boolean。
我們還可以使用Module.cwrap函數為hello函數建立一個JavaScript打包,這樣我們可以使用JS函數多次調用該函數:
const hello = Module.cwrap('myFunction', 'number', null, null)