下载 emsdk
git clone https://github.com/juj/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
新建 hello.c 程序
#include <emscripten/emscripten.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
int main(){
return 0;
}
#ifdef __cplusplus
#define EXTERN extern "C"
#else
#define EXTERN
#endif
EXTERN EMSCRIPTEN_KEEPALIVE int hello(char *buf) {
printf("hello:%s\n", buf);
buf[0] = 'X';
buf[1] = 'X';
buf[2] = 'X';
printf("hello:%s\n", buf);
return 0;
}
新建 temp.html
<button id="mybutton">click</button>
{{{ SCRIPT }}}
<script>
document.getElementById("mybutton").addEventListener("click", () => {
var myTypedArray = new Int32Array([65, 66, 67, 68, 69,0]);
var buf = Module._malloc(myTypedArray.length*myTypedArray.BYTES_PER_ELEMENT);
Module.HEAPU8.set(myTypedArray, buf);
Module.ccall('hello', 'number', ['number'], [buf]);
console.log( Module.HEAPU8[buf]);
console.log( Module.HEAPU8[buf+1]);
console.log( Module.HEAPU8[buf+2]);
console.log( Module.HEAPU8[buf+3]);
Module._free(buf);
});
</script>
编译
emcc -o hello.html hello.c --shell-file temp.html -s NO_EXIT_RUNTIME=1 -s EXPORTED_RUNTIME_METHODS="['ccall']" -s EXPORTED_FUNCTIONS="['_main','_hello', '_malloc','_free']"
把生成文件放到 nginx 上就OK了
hello.wasm
hello.js
hello.html