您的位置:首页 > 其它

[WebAssembly技术]Rust编译成wasm文件

2019-04-03 15:39 1451 查看
版权声明:未经博主允许不得转载(https://github.com/ai-word) https://blog.csdn.net/BaiHuaXiu123/article/details/88997062

WebAssembly (以下简称WASM)最近听到最多的,相对比较火的一个技术,现在主流的浏览器已经完成了对WebAssembly 的初步实现,并且围绕wasm的工具链也日趋完善。
由于 WASM 是静态类型,因此很难直接使用我们熟悉的 JavaScript来直接编写,目前的 WASM 都是通过其他静态语言编译而来。目前支持 WASM 的语言有 C++、Rust、Go等。其中 Rust 对 WASM 的支持度相对完善,社区活跃度也非常高。

1. WebAssembly是什么

通俗讲就是可以用C++,Rust,Go等静态语言编译成wasm二进制文件以供js语言进行加载调用,提高性能

2. WebAssembly特点

1) 运行高效
编译后的二进制文件wasm,js加载运行效率是js的10倍

2) 跨平台
跟js是没有任何耦合关系,用时加载,可移植性非常强

3 )可以解决js一些关键技术性能瓶颈的问题

4) 安全

3. 工具安装操作
1)安装rust工具链

rustup:负责安装 Rust、切换 Rust 版本、下载标准库文件等
rustc:Rust 的编译器(一般通过 Cargo 命令调用)
cargo:Rust 的项目管理工具(类似 Node 的 NPM)
运行:curl https://sh.rustup.rs -sSf | sh即可安装
  1. 安装 WASM 工具链
    wasm-pack 用于将 Rust 项目打包成单个 WASM 文件(类似 Webpack),运行 curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh安装。

  2. 安装wasm_bindgen工具

cargo install wasm_bindgen

4. 具体操作
1) 新建一个rust项目

cargo new wasm-hello
//这里也可以用IDEA编译器直接创建
  1. 在生成的项目src文件夹下面创建一个lib.rs文件

    lib.rs代码
extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn fib(i: u32) -> u32 {
match i {
0 => 0,
1 => 1,
_ => fib(i-1) + fib(i-2)
}
}
  1. 编译成wasm
wasm-pack build


最终会在pkg目录下生成.wasm文件和其他文件,如图所示:

4. js运行加载.wasm文件步骤

  1. 创建index.js 用于加载wasm文件
let squarer;

function loadWebAssembly(fileName) {
return fetch(fileName)
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.compile(buffer))
.then(module => {return new WebAssembly.Instance(module) });
};

loadWebAssembly('wasm_hello_bg.wasm')
.then(instance => {
squarer = instance.exports.fib(12);
console.log('Finished compiling! Ready when you are...',squarer);
});

2)创建index.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>WASM Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h1>WASM Demo</h1>
<script src="./index.js"></script>
</body>
</html>


3)进入到目录运行http-server

http-server

4) 浏览器输入

127.0.0.1:8080

5)运行结果

过程就这么简单

资源下载
资源下载

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐