[WASM] Access WebAssembly Memory Directly from JavaScript
While JavaScript has a garbage-collected heap, WebAssembly has a linear memory space. Nevertheless using a JavaScript ArrayBuffer, we can read and write to WebAssembly’s memory space.
lib.rs:
#[macro_use]
extern crate cfg_if; extern crate wasm_bindgen;
use wasm_bindgen::prelude::*; cfg_if! {
// When the `console_error_panic_hook` feature is enabled, we can call the
// `set_panic_hook` function to get better error messages if we ever panic.
if #[cfg(feature = "console_error_panic_hook")] {
extern crate console_error_panic_hook;
use console_error_panic_hook::set_once as set_panic_hook;
}
} cfg_if! {
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
if #[cfg(feature = "wee_alloc")] {
extern crate wee_alloc;
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
}
} // Definitions of the functionality available in JS, which wasm-bindgen will
// generate shims for today (and eventually these should be near-0 cost!)
//
// These definitions need to be hand-written today but the current vision is
// that we'll use WebIDL to generate this `extern` block into a crate which you
// can link and import. There's a tracking issue for this at
// https://github.com/rustwasm/wasm-bindgen/issues/42
//
// In the meantime these are written out by hand and correspond to the names and
// signatures documented on MDN, for example
#[wasm_bindgen]
extern "C" {
type HTMLDocument;
static document: HTMLDocument;
#[wasm_bindgen(method)]
fn createElement(this: &HTMLDocument, tagName: &str) -> Element;
#[wasm_bindgen(method, getter)]
fn body(this: &HTMLDocument) -> Element; type Element;
#[wasm_bindgen(method, setter = innerHTML)]
fn set_inner_html(this: &Element, html: &str);
#[wasm_bindgen(method, js_name = appendChild)]
fn append_child(this: &Element, other: Element);
#[wasm_bindgen(js_namespace = console)]
fn log(msg: &str);
} macro_rules! log {
($($t:tt)*) => (log(&format!($($t)*)))
}
#[wasm_bindgen]
pub struct Color {
red: u8,
green: u8,
blue: u8,
} #[wasm_bindgen]
pub struct Image {
pixels: Vec<Color>,
} #[wasm_bindgen]
impl Image {
pub fn new() -> Image {
let color1 = Color {
red: 255,
green: 0,
blue: 0,
};
let color2 = Color {
red: 60,
green: 70,
blue: 90,
};
let pixels = vec![color1, color2];
Image {
pixels
}
} pub fn pixels_ptr(&self) -> *const Color {
self.pixels.as_ptr()
}
}
We create a Image object, which has two functions, new() and pixels_ptr() which can be called by javascript. new() is a constructor function, pixels_ptr() is a instant method.
app.js:
import { memory } from "../crate/pkg/rust_webpack_bg";
import { Image } from "../crate/pkg/rust_webpack";
const image = Image.new();
const pixelsPointer = image.pixels_ptr();
const pixels = new Uint8Array(memory.buffer, pixelsPointer, 6);
console.log(pixels);
function numToHex(value) {
const hex = value.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}
function drawPixel(x, y, color) {
const ctx = canvas.getContext("2d");
ctx.fillStyle = `#${numToHex(color[0])}${numToHex(color[1])}${numToHex(
color[2]
)}`;
ctx.fillRect(x, y, 100, 100);
}
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
drawPixel(0, 0, pixels.slice(0, 3));
drawPixel(100, 0, pixels.slice(3, 6));
[WASM] Access WebAssembly Memory Directly from JavaScript的更多相关文章
- [WASM] Read WebAssembly Memory from JavaScript
We use an offset exporting function to get the address of a string in WebAssembly memory. We then cr ...
- WebAssembly让你的Javascript计算性能提升70%
现在的JavaScript代码要进行性能优化,通常使用一些常规手段,如:延迟执行.预处理.setTimeout等异步方式避免处理主线程,高大上一点的会使用WebWorker.即使对于WebWorker ...
- [WASM] Write to WebAssembly Memory from JavaScript
We write a function that converts a string to lowercase in WebAssembly, demonstrating how to set the ...
- Bus,Exclusive access,memory attribute
指令LDREX,STREX是在armv6中新加的指令,配合AMBA3--AXI中的lock[1:0]信号. 在Atomic Access一节中是这么规定的:ARLOCK[1:0]/AWLOCK[1:0 ...
- [WASM] Run WebAssembly in Node.js using the node-loader
WebAssembly is great for targeting performance bottlenecks in the browser. Now with node-loader, we ...
- [中英对照]Introduction to Remote Direct Memory Access (RDMA) | RDMA概述
前言: 什么是RDMA? 简单来说,RDMA就是指不通过操作系统(OS)内核以及TCP/IP协议栈在网络上传输数据,因此延迟(latency)非常低,CPU消耗非常少. 下面给出一篇简单介绍RDMA的 ...
- [WASM] Set up wasm-bindgen for easy Rust/JavaScript Interoperability
Interoperability between JavaScript and Rust is limited to numerics and accessing memory directly. S ...
- WebAssembly完全入门——了解wasm的前世今身
前言 接触WebAssembly之后,在google上看了很多资料.感觉对WebAssembly的使用.介绍.意义都说的比较模糊和笼统.感觉看了之后收获没有达到预期,要么是文章中的例子自己去实操不能成 ...
- JavaScript 的 WebAssembly
本周发布的 Firefox 52 加入了对 WebAssembly 的支持,成为第一个支持 WebAssembly 标准的浏览器,而其它浏览器如 Chrome 57.Safari 和 Edge 也都会 ...
随机推荐
- Python、机器学习、计算机视觉、深度学习入门
1.简明Python教程 2.Python计算机视觉编程 3.机器学习实践 4.吴恩达机器学习 5.李飞飞深度学习与计算机视觉
- DocView mode 3 -- 配置
;在当前页中滚动doc-view-continuous nil ;指定默认的字体大小doc-view-resolution ;gs生成的缓存的目录doc-view-cache-directory
- 【LeetCode】Maximum Depth of Binary Tree(二叉树的最大深度)
这道题是LeetCode里的第104道题. 给出题目: 给定一个二叉树,找出其最大深度. 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数. 说明: 叶子节点是指没有子节点的节点. 示例: 给定 ...
- linux open()文件操作
python程序中经常用到的读文件: f = open("___", 'r') for line in f:#这里每次读取文件的一行,line为字符串,串尾包括了'\n'!!! ...
- [android 开发篇] 易白教程网址
http://www.yiibai.com/android/android_bluetooth.html
- 【JavaScript 7—基础知识点】:BOM
一.基础知识 1.1,什么是BOM BOM(browser object model):也叫浏览器对象模型,它提供了很多对象,用于访问浏览器的功能.BOM缺少规范,每个浏览器提供商又按照自己想法去扩展 ...
- scp命令(基于ssh上传文件等)
(转:http://www.cnblogs.com/hitwtx/archive/2011/11/16/2251254.html) svn 删除所有的 .svn文件 find . -name .svn ...
- BZOJ 3227 [Sdoi2008]红黑树(tree) ——贪心 动态规划
首先可以想到一个贪心的方法,然后一层一层的合并. 也可以采用动态规划的方式,为了写起来好写,把点数*2+1,然后发现在本机上跑不过1500的数据. 交上去居然A掉了. 贪心 #include < ...
- BZOJ 2242 [SDOI2011]计算器 ——EXGCD/快速幂/BSGS
三合一的题目. exgcd不解释,快速幂不解释. BSGS采用了一种不用写EXGCD的方法,写起来感觉好了很多. 比较坑,没给BSGS的样例(LAJI) #include <map> #i ...
- [BZOJ4993||4990] [Usaco2017 Feb]Why Did the Cow Cross the Road II(DP + 线段树)
传送门 f[i][j]表示当前第i个,且最后一个位置连接到j 第一维可以省去,能连边的点可以预处理出来,dp可以用线段树优化 #include <cstdio> #include < ...