1.用c写个方法
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}2.生成wasp模块 两种方式
2.1 在线
https://mbebenita.github.io/WasmExplorer/

2.2 手动编译
#经过一个 git 克隆获取 emscripten git clone https://github.com/juj/emsdk.git #下载,安装并激活 sdk,这个步骤可能须要一点时间 cd emsdk ./emsdk install latest ./emsdk activate latest #让环境生效 source ./emsdk_env.sh #确认安装的内容能够正常运行 emcc --version //编译 emcc add.c -O3 -s WASM=1 -s SIDE_MODULE=1 -s EXPORTED_FUNCTIONS='["_add"]' -o add.wasm //(注:emcc就是Emscripten编译器指令,add.c是输入文件,-s SIDE_MODULE=1表示这就是一个模块, -s EXPORTED_FUNCTIONS表示导出的接口函数,-o add.wasm是输出的文件,更多的命令字可参考官网)
3.加载wasp模块

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Emscripten:Export instance export</title>
</head>
<body>
<p> see console </p>
<script>
function RunWebAssembly(wasmurl) {
return fetch(wasmurl)
.then(response => response.arrayBuffer())
.then(bits => WebAssembly.compile(bits))
.then(module => { return new WebAssembly.Instance(module) });
};
RunWebAssembly('add.wasm')
.then(instance => {
console.log(instance.exports);
//在线编译生成的方法名和自定义的不同,需要调整
alert(instance.exports._Z3addii(2000,21));
//手动编译
//alert(instance.exports.add(2000,21));
});
</script>
</body>
</html>4.不能直接双击运行 需要配置web服务器环境 访问

5.wasm调用javascript //待验证
1.
emscripten_run_script("alert('hi')");2.
#include <emscripten.h>
int main() {
EM_ASM(
alert('hello world!');
throw 'all done';
);
return 0;
}3.
本文为看恩吧原创文章,转载无需和我联系,但请注明来自knsay.com