本Demo的目标
应用WebAssembly
技术,通过浏览器调用C语言
自定义的函数,例子是实现2个变量相加,把计算出来的值返回HTML页面。
我的项目构造
├── index.html└── main.c
C语言
创立文件 main.c
int sum(int v1, int v2){ return v1 + v2;}
HTML
创立文件 index.html
<html><head> <meta charset="utf-8" /> <title>Demo</title></head><body> <div id="result"></div> <script type="text/javascript"> var result; fetch("./main.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { var v1=300; var v2=500; result = instance.exports.sum(300, 500); document.getElementById("result").innerHTML = "调用C函数sum("+v1+","+v2+")后果如下:<br>"+v1+"+"+v2+" = " + result; }); </script></body></html>
编译wasm
将main.c
源码文件编译成main.wasm
文件
emcc main.c -Os -s WASM=1 -s SIDE_MODULE=1 -o main.wasm
执行胜利后
├── index.html├── main.c└── main.wasm
运行一个http服务
将本地文件夹公布到http服务
emrun --no_browser --port 8888 .
实现
浏览器关上 http://localhost:8888/ 即可查看后果。
调用C函数sum(300,500)后果如下:300+500 = 800
留神
WebAssembly是2017年推出的新技术,最好应用最新的浏览器,以反对WebAssembly。