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. day23 02 组合(继续人狗大战游戏)

    day23 02 组合(继续人狗大战游戏) 面向对象的三大特性:继承 多态 封装 先讲解一下组合 组合:一个对象的属性值是另一个类的对象:对象.属性.属性(一般有两个点) 继续扩展day22 01里面 ...

  2. vue 的 scroller 使用

    一 安装 使用npm 安装npm install vue-scroller -d 二 引入 import VueScroller from "vue-scroller" Vue.u ...

  3. 【SaltStack】一些常用模块举例

    一.用户和用户组模块 说明:该sls文件用来在Minion端创建nginx用户和nginx用户组,当创建nginx用户时,对nginx用户组是否已存在做判断! (1)  /srv/salt/creat ...

  4. BRVAH(让RecyclerView变得更高效) (2)

    本文来自网易云社区 作者:吴思博 1.2 宫格和列表的混排样式 关于 Grid 和List 的混排样式,Grid 样式是一行有多个,而 List样式是一行只有一个. 我们可以把 List 样式看成是G ...

  5. 小白用shiro(2)

    本文来自网易云社区 作者:王飞 以上的配置走完以后就可以用,下面讲讲个人需求,以及踩过的坑: 1.如何修改cookie的名称,默认名称"rememberMe"太丑了有木有? 首先丢 ...

  6. nw.js学习地址

    http://blog.sina.com.cn/s/blog_600e56a60102vqj2.html https://github.com/nwjs/nw.js/wiki/Manifest-For ...

  7. 大数据学习——kafka+storm+hdfs整合

    1 需求 kafka,storm,hdfs整合是流式数据常用的一套框架组合,现在 根据需求使用代码实现该需求 需求:应用所学技术实现,kafka接收随机句子,对接到storm中:使用storm集群统计 ...

  8. 如何诊断RAC系统中的'gc cr multi block request'?

    'gc cr multi block request' 是RAC数据库上比较常见的一种等待事件,在RAC 上进行全表扫描(Full Table Scan)或者全索引扫描(Index Fast Full ...

  9. 【(最小权点基)tarjan强连通分量缩点+tarjan模板】HDU 5934 Bomb

    [AC] #include<bits/stdc++.h> using namespace std; typedef long long ll; int n; ; ; const int i ...

  10. poj-2728Desert King(最优比率生成树)

    David the Great has just become the king of a desert country. To win the respect of his people, he d ...