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. laravel中的scope作用域

    laravel中在模板中处理(属于不属于)的数据(增删改查),引入了scope来处理 也就是在模板定义方法中,加上前缀scope laravel中要求在定义的方法scope后面跟的字母要大写 后面那我 ...

  2. java各种数据库连接

    MySQL:       String Driver="com.mysql.jdbc.Driver";    //驱动程序    String URL="jdbc:mys ...

  3. 出现Android.os.NetworkOnMainThreadException 错误

    两种方法解决: 1.如果用的gradle打包,在build.gradle中修改配置 修改SDKVersion 为低版本(7),不能版本降低过多,否则会出现很多不适配. 2.将网络访问放在一个新的线程中 ...

  4. pycharm调整字体大小

    问题:pycharm的默认字体比较小,看起来费眼睛 解决办法: 1.打开 file-->settings 2.Editor-->font 注意:没有修改过的需求先保存一下才能修改size

  5. python的re模块常用方法

    正则表达式模式 模式字符串使用特殊的语法来表示一个正则表达式: 字母和数字表示他们自身.一个正则表达式模式中的字母和数字匹配同样的字符串. 多数字母和数字前加一个反斜杠时会拥有不同的含义. 标点符号只 ...

  6. 读CSS DIV网页样式与布局心得体会

    一.首先根据网页设计图拆分网页的整体结构 二.在html页面用DIV划分出结构块 三.再根据设计图在各个大<DIV>块中加入对应的小<DIV>块或者段落<P>,表单 ...

  7. Leetcode 402.移掉k位数字

    移调k位数字 给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小. 注意: num 的长度小于 10002 且 ≥ k. num 不会包含任何前导零. 示例 1 : ...

  8. 【SVN】http和https的区别

    导读:输入网址的时候,经常输入http://什么什么的,但http是什么,一直都不知道.然后,这回在SVN的学习中,又出现了http和https,而且还有说https的8443端口相对优越,我就在想, ...

  9. soa服务治理

    SOA服务治理 文章:SOA 治理简介 文章:中小型互联网公司微服务实践-经验和教训

  10. 信息安全试验-DES加密!

    信息安全试验二--DES加密算法 本渣表示没有理解原理,照着书上敲了一发,运行无误! 吐槽:手动S盒简直丧心病狂,扩展置换表全是手动输入,加密原理还是很好理解,两次异或,先混淆. 此代码数据由老师给出 ...