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的更多相关文章

  1. [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 ...

  2. WebAssembly让你的Javascript计算性能提升70%

    现在的JavaScript代码要进行性能优化,通常使用一些常规手段,如:延迟执行.预处理.setTimeout等异步方式避免处理主线程,高大上一点的会使用WebWorker.即使对于WebWorker ...

  3. [WASM] Write to WebAssembly Memory from JavaScript

    We write a function that converts a string to lowercase in WebAssembly, demonstrating how to set the ...

  4. Bus,Exclusive access,memory attribute

    指令LDREX,STREX是在armv6中新加的指令,配合AMBA3--AXI中的lock[1:0]信号. 在Atomic Access一节中是这么规定的:ARLOCK[1:0]/AWLOCK[1:0 ...

  5. [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 ...

  6. [中英对照]Introduction to Remote Direct Memory Access (RDMA) | RDMA概述

    前言: 什么是RDMA? 简单来说,RDMA就是指不通过操作系统(OS)内核以及TCP/IP协议栈在网络上传输数据,因此延迟(latency)非常低,CPU消耗非常少. 下面给出一篇简单介绍RDMA的 ...

  7. [WASM] Set up wasm-bindgen for easy Rust/JavaScript Interoperability

    Interoperability between JavaScript and Rust is limited to numerics and accessing memory directly. S ...

  8. WebAssembly完全入门——了解wasm的前世今身

    前言 接触WebAssembly之后,在google上看了很多资料.感觉对WebAssembly的使用.介绍.意义都说的比较模糊和笼统.感觉看了之后收获没有达到预期,要么是文章中的例子自己去实操不能成 ...

  9. JavaScript 的 WebAssembly

    本周发布的 Firefox 52 加入了对 WebAssembly 的支持,成为第一个支持 WebAssembly 标准的浏览器,而其它浏览器如 Chrome 57.Safari 和 Edge 也都会 ...

随机推荐

  1. 数据结构之--图(Graphics)

    1.1:图的定义和术语   图是一种比线性表和树更为复杂的数据结构.在线性表中,数据元素之间仅有线性关系,每个元素仅有一个直接前驱和一个直接后继:在树形结构中,数据元素之间有着明显的层次关系,并且每一 ...

  2. SpringBoot 多线程

    Spring通过任务执行器(TaskExecutor)来实现多线程和并发编程.使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor.而实际开发中任务一般是非阻 ...

  3. PAT Basic 1053

    1053 住房空置率 在不打扰居民的前提下,统计住房空置率的一种方法是根据每户用电量的连续变化规律进行判断.判断方法如下: 在观察期内,若存在超过一半的日子用电量低于某给定的阈值 e,则该住房为“可能 ...

  4. python基础——10(三元运算符、匿名函数)

    一.三元运算符 本质是if--else--的语法糖 前提:简化if--else--的结构,且两个分支有且只有一条语句 案例: a = 20 b = 30 res = a if a > b els ...

  5. Python内置函数7

    Python内置函数7 1.propertypython内置的一个装饰器可参考https://blog.csdn.net/u013205877/article/details/77804137 2.q ...

  6. 【Luogu】P1602Sramoc问题(堆)

    题目链接 很巧妙的想法.一开始将1~k-1加入堆中,然后每次从堆里取出一个最小的,判断是不是答案,如果不是,那么就枚举新数的末一位加上. 代码如下 #include<cstdio> #in ...

  7. 【Luogu】P3052摩天大楼里的奶牛(状压DP)

    参见ZHT467的题解. f[i]表示在i这个集合下的最少分组数和当前组最少的容量. 从1到(1<<n)-1枚举i,对于每个i枚举它的子奶牛,然后重载运算符计算. 代码如下 #includ ...

  8. POJ 2411 Mondriaan's Dream ——状压DP 插头DP

    [题目分析] 用1*2的牌铺满n*m的格子. 刚开始用到动规想写一个n*m*2^m,写了半天才知道会有重复的情况. So Sad. 然后想到数据范围这么小,爆搜好了.于是把每一种状态对应的转移都搜了出 ...

  9. [luoguP2051] [AHOI2009]中国象棋(DP)

    传送门 注释写明了一切 #include <cstdio> #define N 111 #define p 9999973 #define LL long long int n, m; L ...

  10. vector 类中的 push_back( ) 函数

    函数名 push_back,算法语言里面的一个函数名,如:   1) c++中的vector头文件里面就有这个push_back函数:   2) 在vector类中作用为在vector尾部加入一个数据 ...