如何从js访问WebAssembly中的编译内存

noo*_*ntz 5 javascript c++ webassembly

考虑以下C++:

int MYVAR = 8;
Run Code Online (Sandbox Code Playgroud)

它将从Clang/LLVM编译到插入下面操场的WASM字节码.

为了便于阅读:

(module
(table (;0;) 0 anyfunc)
(memory (;0;) 1)
(global (;0;) i32 (i32.const 0))
(export "MYVAR" (global 0))
(data (i32.const 0) "\08\00\00\00"))
Run Code Online (Sandbox Code Playgroud)

当从js调用时,MYVAR将公开指向变量的指针.

但是如何使用新的js API访问实际内存?

内存构造函数似乎在初始化时删除了条目,但我不确定我是否正确地解释了这一点.

作为旁注,模块没有规范中指定的exports属性,但这也可能是一种误解.

操场:

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>MEMORY ACCESS TEST</title>
</head> 
<div>
<h1 style="display: inline;">MEMORY LOCATION : </h1>
<h1 id='POINTER' style="display: inline;"></h1>
</div> 
<div>
<h1 style="display: inline;">VALUE : </h1>
<h1 id='VALUE' style="display: inline;"></h1>
</div>
<body>
<script>
 var bytecode = new Uint8Array([
 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00, 0x04, 0x84,
 0x80, 0x80, 0x80, 0x00, 0x01, 0x70, 0x00, 0x00, 0x05, 0x83,
 0x80, 0x80, 0x80, 0x00, 0x01, 0x00, 0x01, 0x06, 0x86, 0x80,
 0x80, 0x80, 0x00, 0x01, 0x7F, 0x00, 0x41, 0x00, 0x0B, 0x07,
 0x89, 0x80, 0x80, 0x80, 0x00, 0x01, 0x05, 0x4D, 0x59, 0x56,
 0x41, 0x52, 0x03, 0x00, 0x0B, 0x8A, 0x80, 0x80, 0x80, 0x00,
 0x01, 0x00, 0x41, 0x00, 0x0B, 0x04, 0x08, 0x00, 0x00, 0x00,
 0x00, 0x96, 0x80, 0x80, 0x80, 0x00, 0x07, 0x6C, 0x69, 0x6E,
 0x6B, 0x69, 0x6E, 0x67, 0x03, 0x81, 0x80, 0x80, 0x80, 0x00,
 0x04, 0x04, 0x81, 0x80, 0x80, 0x80, 0x00, 0x04
 ]);
 WebAssembly.instantiate(bytecode).then(function(wasm) {
 console.log(wasm.module);
 console.log(wasm.instance);
 let pointer = wasm.instance.exports.MYVAR;
 document.getElementById('POINTER').innerHTML = pointer; 
 let memory = new WebAssembly.Memory({initial : 1});
 let intView = new Uint32Array(memory.buffer);
 document.getElementById('VALUE').innerHTML = intView[pointer];
 });
 </script>
 </body>

 </html>
Run Code Online (Sandbox Code Playgroud)

JF *_*ien 2

MYVAR是一个全球性的。这是与内存部分完全独立的可寻址单元。它包含单独的标量值。

您似乎正在尝试访问“内存”部分。您确实可以使用i32全局作为指针,就像使用任何其他指针一样i32,但它无法自动访问内存。你也必须导出你的记忆!

尝试:

(module
(table (;0;) 0 anyfunc)
(memory (;0;) 1)
(global (;0;) i32 (i32.const 0))
(export "MYVAR" (global 0))
(export "MYMEM" (memory 0)) ;; New!
(data (i32.const 0) "\08\00\00\00"))
Run Code Online (Sandbox Code Playgroud)

和:

WebAssembly.instantiate(bytecode).then(function(wasm) {
 console.log(wasm.module);
 console.log(wasm.instance);
 let pointer = wasm.instance.exports.MYVAR;
 document.getElementById('POINTER').innerHTML = pointer; 
 let memory = wasm.instance.exports.MYMEM; // New!!
 let intView = new Uint32Array(memory.buffer);
 document.getElementById('VALUE').innerHTML = intView[pointer];
 });
Run Code Online (Sandbox Code Playgroud)