一、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)