美文网首页
WebAssembly quick start

WebAssembly quick start

作者: simpleYin | 来源:发表于2018-04-23 20:32 被阅读0次

    参考: google WebAssembly Introducation

    1. 安装准备

    1. Git
    2. CMake
    3. Host system compiler
    4. Python 2.7

    2. 下载编译工具

    1. install emsdk (emsdk(Emscripten toolchain) 是一个预编译的工具链) Link

    2. 执行命令:

    MacBook-Pro-6:hello mac$ emcc hello.c -Os -s WASM=1 -s SIDE_MODULE=1 -o hello.wasm
    

    可能会报错:

    Traceback (most recent call last):
    
    File "/Users/mac/Documents/WebAssembly/emsdk/emscripten/1.37.22/emcc", line 5, in <module>
    
    from tools.toolchain_profiler import ToolchainProfiler
    
    ImportError: No module named tools.toolchain_profiler
    

    原因:安装时失败,重装即可。

    3. 使用.wasm文件

    1. wasm作为一个模块导入进来,依靠JS API得到模块中的函数,如下

    2. 编写C文件(gen.c):

    #include<stdio.h>
    
    int add(int i, int j) {
    
    return i + j;
    
    }
    

    4. 使用emcc 编译

    *   emcc gen.c -s ONLY_MY_CODE=1 -s WASM=1 -s EXPORTED_FUNCTIONS="['_add']" -o gen.js
    

    在上面的命令行中,_add函数作为gen.c中add函数的导出名。

    1. 在js中调用
    var  add = new Function();
    
    const memory = new WebAssembly.Memory({ initial: 256, maximum: 256 });
    
    const importObj = {
    
    env: {
    
    abortStackOverflow: () => { throw new Error('overflow'); },
    
    table: new WebAssembly.Table({ initial: 0, maximum: 0, element: 'anyfunc' }),
    
    tableBase: 0,
    
    memory: memory,
    
    memoryBase: 1024,
    
    STACKTOP: 0,
    
    STACK_MAX: memory.buffer.byteLength,
    
    }
    
    };
    
    fetch('gen.wasm').then((response) => response.arrayBuffer())
    
    .then((bytes) => WebAssembly.instantiate(bytes, importObj))
    
    .then((wa) => add = wa.instance.exports._add);
    
    //若出现Link_error,则检查importObj中是否未包含错误提示中指出的关键字。
    

    5. 参数传递

    1. 若现在用C编写一个对整数数组进行排序的算法,将其编译为wasm,如何在JS中调用并传递数组参数?
      Ans: 参见:pass array to C function with emscripten

    相关文章

      网友评论

          本文标题:WebAssembly quick start

          本文链接:https://www.haomeiwen.com/subject/ufqrlftx.html