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. tiny4412 busybox制作根文件系统rootfs nfs 挂载 ubuntu 14.04

    http://blog.csdn.net/liudijiang/article/details/50555429(转) 首先得要有制作好的uboot和linux内核镜像zImage,先烧录到sd卡里, ...

  2. (转)UILabel常用属性

    Java代码 收藏代码 #import "ViewController.h" #import <CoreText/CoreText.h> @interface View ...

  3. JavaScript正则表达式-非捕获性分组

    非捕获性分组定义子表达式可以作为整体被修饰但是子表达式匹配结果不会被存储. 非捕获性分组通过将子表达式放在"?:"符号后. str = "img1.jpg,img2.jp ...

  4. 10大mysql需要注意的参数

    MySQL变量很多,其中有一些MySQL变量非常值得我们注意,下面就为您介绍一些值得我们重点学习的MySQL变量,供您参考. 1 Threads_connected 首先需要注意的,想得到这个变量的值 ...

  5. 【RAID】raid1 raid2 raid5 raid6 raid10的优缺点和做各自raid需要几块硬盘

    Raid 0:一块硬盘或者以上就可做raid0优势:数据读取写入最快,最大优势提高硬盘容量,比如3快80G的硬盘做raid0 可用总容量为240G.速度是一样.缺点:无冗余能力,一块硬盘损坏,数据全无 ...

  6. 开源中国+soucetree

    参考链接:http://www.cocoachina.com/programmer/20151012/13682.html 1.创建一个工程

  7. HDU——1045Fire Net(最大匹配)

    Fire Net Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total S ...

  8. 算法复习——无源汇可行流(zoj2314)

    题目: The terrorist group leaded by a well known international terrorist Ben Bladen is buliding a nucl ...

  9. 路飞学城详细步骤 part2

    一 显示课程列表 需求:当你点击课程,course.vue在 <router-view>渲染,并不需要你进行其他点击,所欲的课程列表直接在前端显示,数据是从数据库拿到的. 补充1:生命周期 ...

  10. Linux(14):集群架构进阶 --- CentOS 7

    CentOS 7 CentOS 7 管理软件常用命令: vim /etc/selinux/config # 修改 SELINUX 开机自启动与否 setenforce 0 # 关闭 SELINUX g ...