天天看點

WebAssembly:wasm探索與TypeScript子產品wasm應用

目錄

安裝編譯環境

HelloWorld 

Emscripten/bind實踐

TypeScript子產品WASM引用

更多相關連結

安裝編譯環境

前置條件: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

繼續閱讀