目录
安装编译环境
前置条件:git\cmake\python\node。
编译安装Emscripten
通过 Emscripten SDK 构建 Emscripten 是自动的,下面是步骤。
$ git clone https://github.com/juj/emsdk.git
$ cd emsdk
$ ./emsdk install sdk-incoming-64bit binaryen-master-64bit
$ ./emsdk activate sdk-incoming-64bit binaryen-master-64bit
这些步骤完成以后,安装完成。将 Emscripten 的环境变量配置到当前的命令行窗口下。
$ source ./emsdk_env.sh
这条命令将相关的环境变量和目录入口将会配置在当前的命令行窗口中。
HelloWorld
创建文件helloWorld.cpp:
#include <iostream>
int main() {
std::cout << "Hello World!" << std::endl;
}
终端运行:
emcc helloWorld.cpp
会生成a.out.js与a.out.wasm;
终端运行生成文件:
node a.out.js
终端提示:hello world!
Emscripten/bind实践
1.函数生声明文件示例(helloWorld.h)
#ifndef INPUTNUMBER
#define INPUTNUMBER
#include <string>
int scaled(int srcWidth, int srcHeight, int destWidth, int destHeight);
std::string stringd();
#endif //INPUTNUMBER
2.函数定义文件示例(helloWorld.cpp)
#include "helloWorld.h"
int scaled(int srcWidth , int srcHeight, int destWidth, int destHeight)
{
return srcWidth + srcHeight;
}
std::string stringd()
{
return "zouzouzou";
}
3.绑定函数文件示例(helloWorldBind.bind.cpp)
#include <emscripten/bind.h>
#include "texture-scale.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(core_module) {
function("scaled", &scaled);
function("stringd", &stringd);
}
终端运行编译命令:
emcc --bind -o ../src/helloWorld.js -s MODULARIZE=1 -s EXPORT_NAME=HelloWorldModule -Wall -Werror src/helloWorld.cpp src/helloWorld.bind.cpp
TypeScript模块WASM引用
1.对上述生成的JS文件生成一个.d.s声明文件示例:
// 需要用下面的指令安装emscripten类型:yarn install --save-dev @types/emscripten
// 然后就能使用 EmscriptenModuleFactor、EmscriptenModule等类型。
interface HelloWorldModuleWithBindings extends EmscriptenModule {
scaled: (srcWidth: number, srcHeight: number, destWidth: number, destHeight: number) => number;
stringd: () => string;
}
declare const Lt3DCoreModule: EmscriptenModuleFactory<Lt3DCoreModuleWithBindings>;
export default Lt3DCoreModule;
2.模块应用
import HelloWorldModule from "./HelloWorld";
let moduleOverrides: Partial<EmscriptenModule> = {
print: (s) => {
console.log(s);
},
printErr: (e) => {
console.error(e);
}
};
Lt3DCoreModule(moduleOverrides).then((Module) =>
{
//console.log("load HelloWorldModule success.", Module);
let result: number = Module.scaled(123, 456, 200, 200);
console.log(result, result == 123 * 456);
console.log(Module.stringd());
}).catch((error) => {
console.log("load HelloWorldModule failed with error:", error);
});
更多相关链接
https://developer.mozilla.org/en-US/docs/WebAssembly
https://developer.mozilla.org/en-US/docs/WebAssembly/C_to_wasm