WebAssembly编译
环境:centos 7.9
1、准备环境
sudo yum install docker sudo systemctl start docker.service sudo docker pull trzeci/emscripten:latest
2、编写C++源文件
//main.cpp #include<stdio.h> #include<string> #include<cstring> #ifdef __EMSCRIPTEN__ #include<emscripten.h> #endif int main() { return 0; } extern "C"{ #ifdef __EMSCRIPTEN__ EMSCRIPTEN_KEEPALIVE #endif int add(int x,int y) { return x + y; } #ifdef __EMSCRIPTEN__ EMSCRIPTEN_KEEPALIVE #endif int min(int x,int y) { return x -y; } #ifdef __EMSCRIPTEN__ EMSCRIPTEN_KEEPALIVE #endif char* get(char* a) { return a; } #ifdef __EMSCRIPTEN__ EMSCRIPTEN_KEEPALIVE #endif char* data(char* a) { *a = '\0'; char name[] = "hello from native code."; strcat(a,name); return a; } #ifdef __EMSCRIPTEN__ EMSCRIPTEN_KEEPALIVE #endif int get_data(char* name,int lenth,char* onoutput) { char str[260]={0}; sprintf(str,"name:%s,lenth:%d,from native code.",name,lenth); strcpy(onoutput,str); return strlen(str); } }
3、启动docker,并将main.cc文件拷贝至docker中进行编译。
sudo docker run -ti 7634ecdacf21 /bin/bash
编译指令:
emcc main.cpp -o main.js -s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap','UTF8ToString']
编译后,产生如下main.js 和main.wasm文件。
4、测试
将main.js、main.wasm(两个文件存放目录一致)拷贝到web容器中,并编写main.html测试页面。
<html> <head> <meta charset="utf-8"> <title>WebAssemble Demo</title> </head> <body> <button onclick="fun_add()">add</button> <button onclick="fun_min()">min</button> <button onclick="fun_get()">get</button> <button onclick="fun_data()">data</button> <button onclick="fun_get_data()">get_data</button> <div id="log"></div> <script> function fun_add() { const add=Module.cwrap('add','number',['number,number']); log.innerHTML=("add(12,5)的计算结果:" + add(12, 5)); } function fun_min() { const min=Module.cwrap('min','number',['number','number']); log.innerHTML=("min(12,5)的计算结果:" + min(12, 5)); } function fun_get() { const get = Module.cwrap('get','string',['string']); log.innerHTML=get('汉语-hanyu-demo!'); } function fun_data() { const data = Module.cwrap('data','string',['string']); log.innerHTML=data(''); } function fun_get_data() { let onoutput=""; const pointer = Module._malloc(256); const get_data = Module.ccall('get_data','number',['string','number','number'],['hello from web',129,pointer]); onoutput = Module.UTF8ToString(pointer); log.innerHTML=onoutput; Module._free(pointer) } </script> <script src="democpp.js"></script> </body> </html>
在浏览器中输入main.html页面请求地址,分别点击[add]、[min]、[ge]三个按钮进行测试,实验效果如下图所示: