本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。