[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 也都会 ...
随机推荐
- 继上次编译openwrt之后,添加web界面
上编博客写了关于openwrt编译环境和编译一个默认配置的openwrt系统. 现在我正在做如何添加web界面.(hiwooya自带的luci web) 方法如下: 首先在编译环境中配置 make m ...
- shell-code-exerciese-1
&&&&&&&&&&&&&&&&&&&& ...
- PYDay10&11&12&13-常用模块:time|datetime|os|sys|pickle|json|xml|shutil|logging|paramiko、configparser、字符串格式化、py自动全局变量、生成器迭代器
1.py文件自动创建的全局变量 print(vars()) 返回值:{'__name__': '__main__', '__package__': None, '__loader__': <_f ...
- Java-列出一个类实现的所有接口
package com.tj; public class MyClass2 { public static void main(String[] args) { Class cls = java.la ...
- Matplotlib基本图形之直方图
Matplotlib基本图形之直方图 直方图特点 由一系列高度不等的纵向条形组成,表示数据分布情况例如年级同学身高分布注意与条形图的区别 示例代码: import osimport numpy as ...
- 指定字符串 s,返回 s 所有可能的子串,每个子串必须是一个回文(指顺读和倒读都一样的字符串)
Given a string s, partition s such that every substring of the partition is a palindrome Return all ...
- [android开发篇]项目目录结构
- 九度oj 题目1090:路径打印
题目描述: 给你一串路径,譬如:a\b\c a\d\e b\cst d\你把这些路径中蕴含的目录结构给画出来,子目录直接列在父目录下面,并比父目录向右缩一格,就像这样:a b c d ...
- Nginx出现403 forbidden(Permission denied)报错的四种方法
查看nginx的error.log日志.打开日志出现Permission denied: 1.启动用户和nginx的工作用户不一致所致 查看nginx的启动用户,发现是www,而为是用root启动的 ...
- nginx反向代理,负载均衡,动静分离,rewrite地址重写介绍
一.rewrite地址重写 地址转发后客户端浏览器地址栏中的地址显示是不变的,而地址重写后地址栏中的地址会变成正确的地址. 在一次地址转发过程中只会产生一次网络请求,而一次地址重写产生两次请求. 地址 ...