Hot For Coding
WebAssembly简单试用例子

webassembly

WebAssembly自从提出,就一直被火热关注,前端性能至少有了一个解决方案,我们试着写一个小例子。

安装环境

以Mac系统为例子

  • 安装cmake brew install cmake
  • 安装Python 2.7.X brew install python2
  • 安装GCC (Mac自带)
  • 安装Git (Mac自带)

校验环境

确认git, pythoncmake命令可以用

cmake

# cmake --version
cmake version 3.10.1
 
CMake suite maintained and supported by Kitware (kitware.com/cmake).
@Nicholas-MBP ➜ WebAssembly 

python

# python -V
Python 2.7.10

git

# git --version
git version 2.14.3 (Apple Git-98)

安装工具链

安装Aseembly SDK

git clone https://github.com/juj/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest

PATH设置

source ./emsdk_env.sh --build=Release

运行一个简单的例子

hello.c

int doubler(int x) {
  return 2 * x;
}

生成hello.wasm

emcc hello.c -Os -s WASM=1 -s SIDE_MODULE=1 -o hello.wasm

hello.js

function loadWebAssembly(filename, imports) {
  // Fetch the file and compile it
  return fetch(filename)
    .then(response => response.arrayBuffer())
    .then(buffer => WebAssembly.compile(buffer))
    .then(module => {
      // Create the imports for the module, including the
      // standard dynamic library imports
      imports = imports || {};
      imports.env = imports.env || {};
      imports.env.memoryBase = imports.env.memoryBase || 0;
      imports.env.tableBase = imports.env.tableBase || 0;
      if (!imports.env.memory) {
        imports.env.memory = new WebAssembly.Memory({ initial: 256 });
      }
      if (!imports.env.table) {
        imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' });
      }
      // Create the instance.
      return new WebAssembly.Instance(module, imports);
    });
}
 
// Main part of this example, loads the module and uses it.
loadWebAssembly('hello.wasm')
  .then(instance => {
    var exports = instance.exports; // the exports of that instance
    console.log(exports._doubler(55)) // Output: 110
  }
);

运行下,不出意外的话Console打印110

TITLE: WebAssembly简单试用例子

LINK: https://www.qttc.net/492_webassembly_example.html

NOTE: 转载内容请注明出处