环境准备:
lunix下docker
参考https://hub.docker.com/r/emscripten/emsdk
拉编译环境
docker pull emscripten/emsdk
编译
随便找个目录,敲下面命令,编译一个webAssembly 程序
# create helloworld.cpp
cat << EOF > helloworld.cpp
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
EOF
# compile with docker image
docker run \
--rm \
-v $(pwd):/src \
trzeci/emscripten \
emcc helloworld.cpp -o helloworld.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS和C互相操作</title>
</head>
<body>
<script>
Module = {};
Module.onRuntimeInitialized = function (){
console.log(Module._show_me_your_name());
console.log(Module._add(1,2))
}
</script>
<script src="./helloworld.js"></script>
</body>
</html>
上述的html文件对应下面这个cpp
EM_PORT_API(int) show_me_your_name() {
return 789;
}
EM_PORT_API(float) add(float a,float b){
return a + b;
}
同样的编译方式,试一下
上述是最简单的demo,js环境跟wasm的交互,只有number是直通的,如果是字符串需要做其他的转化处理,以后再说
其他:
docker pull镜像的时候可能会出错,docker配置代理的方式
进 /etc/docker/daemon.json配置
{
"registry-mirrors": [
"https://registry.hub.docker.com",
"http://hub-mirror.c.163.com",
"https://docker.mirrors.ustc.edu.cn",
"https://registry.docker-cn.com"
],
"proxies": {
"http-proxy": "http://xxx:8118",
"https-proxy": "http://xxx:8118",
"no-proxy": "localhost"
}
}
重启服务
systemctl daemon-reload
systemctl restart docker
xxx这些自行根据实际情况替换
参考:
https://www.wenjiangs.com/doc/afky6syw
墨滴社区
Download and install — Emscripten 3.1.66-git (dev) documentation