WebAssembly简单试用例子
JavaScript
2018-01-11
WebAssembly自从提出,就一直被火热关注,前端性能至少有了一个解决方案,我们试着写一个小例子。
一、安装环境
以OS X系统为例子,
安装cmake
# brew install cmake
安装Python 2.7.X
# brew install python2
安装GCC
因为我已经安装了Xcode,所以忽略此步,如果你没有安装GCC可以自己搜索相关文档安装
安装 GIT
OS X自带,如果的系统没有自带,可以先搜索相关文档安装
二、校验环境
确认 git python cmake 命令可以用
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)
三、安装工具链
安装
$ 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
相关博文
换一组Comments 0
Hi,你想第一个做沙发么?
乳名?小名?昵称?网名?均可
email,放心,我不会给你乱投广告的
想获得回访就把你的站点URL写上(没有留空)
[NOTICE]木要投放广告
[NOTICE]木要骂人,说不该说的话
[NOTICE]自由言论,但要遵纪守法