WebAssembly入门demo

字数统计: 578阅读时长: 2 min
2019/05/12 Share
一、准备工作

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Get the emsdk repo
git clone https://github.com/emscripten-core/emsdk.git

# Enter that directory
cd emsdk

# Fetch the latest version of the emsdk (not needed the first time you clone)
git pull

# Download and install the latest SDK tools.
./emsdk install latest

# Make the "latest" SDK "active" for the current user. (writes ~/.emscripten file)
./emsdk activate latest

# Activate PATH and other environment variables in the current terminal
source ./emsdk_env.sh
二、好了,开始写demo

功能:js传递给c一个字符串,c返回给js一个字符串

1、新建一个目录,创建两个文件index.html和main.cpp

2、main.cpp内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <emscripten.h>
using namespace std;

extern "C" {

EMSCRIPTEN_KEEPALIVE
const char* jsCallC(const char* jsStr) {
cout << jsStr << endl;

const char* result = "hi from c";
return result;
}

}
  • 给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
2
3
4
5
6
7
8
9
10
11
emsdkDir='emsdk的路径'
emsdk activate latest
source ${emsdkDir}/emsdk_env.sh

emcc main.cpp \
-std=c++11 \
-s WASM=1 \
-s MODULARIZE=1 \
-s EXTRA_EXPORTED_RUNTIME_METHODS=["allocateUTF8","UTF8ToString"] \
-s EXPORTED_FUNCTIONS=["_jsCallC"] \
-O0 -o webassembly.js
  • 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

  • 浏览器打开http://localhost:8080/

三、编译参数说明

*https://github.com/emscripten-core/emscripten/blob/master/src/settings.js

原文作者:大瑞

原文链接:https://ruizhang81.github.io/2019/05/12/WebAssembly入门demo/

发表日期:May 12th 2019, 3:30:27 pm

更新日期:May 12th 2019, 3:30:43 pm

版权声明:

CATALOG
  1. 1. 一、准备工作
  2. 2. 二、安装编译工具(从c++编译到wasm和asm)
  3. 3. 二、好了,开始写demo
  4. 4. 三、编译参数说明