一、准备工作
1、安装xcode command tools(已经安装请略过)1
xcode-select --install
2、安装python(已经安装请略过)1
brew install python
3、安装git(已经安装请略过)1
brew install git
4、安装cmake(已经安装请略过)
1 | brew install cmake |
二、安装编译工具(从c++编译到wasm和asm)
1 | # Get the emsdk repo |
二、好了,开始写demo
功能:js传递给c一个字符串,c返回给js一个字符串
1、新建一个目录,创建两个文件index.html和main.cpp
2、main.cpp内容
1 | #include <iostream> |
- 给js调用的方法必须标注EMSCRIPTEN_KEEPALIVE
- 打印js传进来的字符串,再返回一个字符串给js
3、index.html内容1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26<!DOCTYPE html>
<html>
<head>
<script src="./webassembly.js"></script>
</html>
<script type="text/javascript">
function fun(){
var say2c = "hi from js"
var inputPtr = ModuleWASM_INSTANCE.allocateUTF8(say2c) //字符串转指针
var outputPtr = ModuleWASM_INSTANCE._jsCallC(inputPtr) //js call c
var outputStr = ModuleWASM_INSTANCE.UTF8ToString(outputPtr) //排序结果指针转字符串
ModuleWASM_INSTANCE._free(inputPtr) //释放申请的指针
console.log(outputStr);
}
//初始化webasembly
const ModuleWASM_INSTANCE = Module();
ModuleWASM_INSTANCE.onRuntimeInitialized = function() {
console.log("ModuleWASM_INSTANCE init finish")
fun()
}
</script>
4、编译
1 | emsdkDir='emsdk的路径' |
- WASM=1 生成wasm文件而不是生成asm文件
- MODULARIZE=1 生成js闭包模块
- EXTRA_EXPORTED_RUNTIME_METHODS 提供字符串转指针,指针转字符串方法
- EXPORTED_FUNCTIONS 提供js c的方法(注意前面有个下划线)
- -O0 编译优化级别是0,也可以是1,2,3 越大编译优化越大
- -o webassembly.js 指定生成文件名
启动服务在控制台看看效果:
- python2:python -m SimpleHTTPServer 8080
python3:python -m http.server 8080
三、编译参数说明
*https://github.com/emscripten-core/emscripten/blob/master/src/settings.js