[WASM] Write to WebAssembly Memory from JavaScript

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

WASM Fiddle: https://wasdk.github.io/WasmFiddle/?h1s69

Demo Repo: https://github.com/guybedford/wasm-intro

We want to create a funcrtion ‘toLowerCase‘, which enable JS to write in Memory.

To write data into WASM, we need to variables in C code, one is ‘inStr‘ which get original input (for example ‘Hello World‘), another is ‘outStr‘ which will transform to lower case string (for example: ‘hello world‘).

C code:

void consoleLog (char* offset, int len);

char inStr[20];
char outStr[20];

char* getInStrOffset () {
  return &inStr[0];
}

void toLowerCase() {
  for (int i = 0; i < 20; i++ ) {
    char c = inStr[i];
    if (c > 64 &&  c < 91) {
      c = c + 32;
    }
    outStr[i] = c;
  }
  consoleLog(&outStr[0], 20);
}

JS: Some code to get wasm instance.

var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, {
  env: {
    consoleLog (offset, len) {
      const strBuf = new Uint8Array(mem.buffer, offset, len);
      log(new TextDecoder().decode(strBuf));
    }
  }
});
const mem = wasmInstance.exports.memory;

Now we need to write data from JS to WASM memory, the way to do it is just to put data into ‘inStr‘:

const mem = wasmInstance.exports.memory;

function writeString (str, offset) {
  const strBuf = new TextEncoder().encode(str);
  const outBuf = new Uint8Array(mem.buffer, offset, strBuf.length);

      for (let i = 0; i < strBuf.length; i++) {
        outBuf[i] = strBuf[i];
      }
  }
}

writeString(‘Hello Web Assembly‘, wasmInstance.exports.getInStrOffset());

Because what ‘wasmInstance.exports.getInStrOffset()‘ return us is the first char address of ‘inStr‘, then we use for loop to write data into ‘inStr‘.

After writting the data, then we can call ‘toLowerCase‘ to see the result:

var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, {
  env: {
    consoleLog (offset, len) {
      const strBuf = new Uint8Array(mem.buffer, offset, len);
      log(new TextDecoder().decode(strBuf));
    }
  }
});
const mem = wasmInstance.exports.memory;

function writeString (str, offset) {
  const strBuf = new TextEncoder().encode(str);
  const outBuf = new Uint8Array(mem.buffer, offset, strBuf.length);

      for (let i = 0; i < strBuf.length; i++) {
        outBuf[i] = strBuf[i];
      }
  }
}

writeString(‘Hello Web Assembly‘, wasmInstance.exports.getInStrOffset());
wasmInstance.exports.toLowerCase();
时间: 2025-01-09 03:30:14

[WASM] Write to WebAssembly Memory from JavaScript的相关文章

(翻译) How variables are allocated memory in Javascript? | scope chain | lexicial scope

总结: 阅读下面文章需要15分钟 提问者的问题是JavaScript中内存是怎么分配的,在介绍的过程作者涉及计到了JS中 Scope Chain和调用函数call生成lexicial environment和environment record(被作者合并称为 binding objects)的过程.非常值得一看     个人翻译: How variables are allocated memory in Javascript? It's actually a very interesting

对于WebAssembly编译出来的.wasm文件js如何调用

WebAssembly也叫浏览器字节码技术 这里就不过多的解释了网上很多介绍 主要是让大家知道在js里面如何调用执行它,我之前看WebAssemblyAPI时候反正是看得一脸懵逼 也是为了大家能更快的入手这个比较新的技术吧 这边写的一个dom是官方推荐的c/c++编译的 c代码 1 int add (int x, int y) { 2 return x + y; 3 } 4 5 int square (int x) { 6 return x * x; 7 } 属性c但是对字节码不熟悉的朋友可能会

webpack打包---报错内存溢出javaScript heap out of memory

今天, npm run build打包时,又报内存溢出了.所以记录一下,之前查了博客有一些解释. “报错CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory是 JavaScript堆内存不足,这里说的 JavaScript 其实就是 Node,我们都知道 Node 是基于V8引擎,在一般的后端开发语言中,在基本的内存使用上没有什么限制. 但是我去查阅了相关的资料才发现,在 Node 中通过 JavaScript

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

现在的JavaScript代码要进行性能优化,通常使用一些常规手段,如:延迟执行.预处理.setTimeout等异步方式避免处理主线程,高大上一点的会使用WebWorker.即使对于WebWorker也仅仅是解决了阻塞主线程的问题,但是对于JavaScript计算性能慢的问题并没有解决.这里对一些需要密集计算的场景我给大家推荐一个神器——WebAssembly.在目前阶段,WebAssembly 适合大量密集计算.并且无需频繁与 JavaScript 及 DOM 进行数据通讯的场景.比如游戏渲染

WebAssembly,可以作为任何编程语言的编译目标,使应用程序可以运行在浏览器或其它代理中——浏览器里运行其他语言的程序?

Mozilla.谷歌.微软和苹果已经决定开发一种面向Web的二进制格式.该格式名为WebAssembly,可以作为任何编程语言的编译目标,使应用程序可以运行在浏览器或其它代理中. 几年前,我们在InfoQ上讨论过面向Web的通用字节码的优点(见<讨论:我们是否需要一种通用的Web字节码?>),概括了创建这样一种格式的困难.其中提及的一个主要问题是主要的浏览器制造商无法达成一致:Mozilla在推asm.js,谷歌支持PNaCI,苹果在开发FLTJIT,而微软没有对其中的任何一种表示出兴趣.但现

WebAssembly系列2-为什么我们需要WebAssembly—采访Brendan Eich

在2015.06.17, JavaScript之父Brendan Eich宣布了一个新项目:将新的底层功能(low level primitives)带入web中[1],?这将使在浏览器或其他JavaScript环境中采用类似于C & C++等语言编写的项目的编译更加容易.如果是第一次听到这个想法,可参见阅读"What is WebAssembly"的基本描述[3]. WebAssembly团队包括来自Google, Microsoft, Mozilla, Apple, 以及W

[转帖]几张图让你看懂WebAssembly

几张图让你看懂WebAssembly https://www.jianshu.com/p/bff8aa23fe4d (图片来源:giphy.com) 编者按:本文由明非在众成翻译平台上翻译. 最近,WebAssembly 在 JavaScript 圈非常的火!人们都在谈论它多么多么快,怎样怎样改变 Web 开发领域.但是没有人讲他到底为什么那么快.在这篇文章里,我将会帮你了解 WebAssembly 到底为什么那么快. 第一,我们需要知道它到底是什么!WebAssembly 是一种可以使用非 J

The JavaScript World Domination

From browsers to mobile phones, from tablets to tabletops, from industrial automation to the tiniest microcontrollers?-?JavaScript seems to creep into the most unexpected places these days. It's not too long until your very toaster will be running Ja

对JavaScript中闭包的理解

相信很多人都有看过关于闭包的文章,但是真正意义上的了解清楚的也不多,今天我们就来谈谈对闭包的理解. 闭包在JavaScript中一直是一个很重要的存在,闭包很重要但是又很难理解,起初我也是这样认为,但只要真的清楚之后,你会觉得很有趣. 我们先来看一个闭包的例子: 1 function foo() { 2 let a = 2; 3 function bar() { 4 console.log(a); 5 } 6 return bar; 7 } 8 let baz = foo(); 9 baz();