2017-09-04 57 views
2

考慮下面的C++中WebAssembly編譯內存:如何訪問從JS

int MYVAR = 8; 

這將彙編從鏘/ LLVM到插在下面的操場WASM字節碼。

WAST出於可讀性:從JS調用時

(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")) 

MYVAR將暴露的指針變量。

但是,如何使用新的js API訪問實際內存?

內存構造函數似乎初始化時刪除條目,但我不知道我是否正確解釋此。

作爲一個側面說明,作爲specs指定的模塊不具有出口的財產,但這再次,可能是一個誤解。

遊樂場:

<!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> 

回答

1

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")) 

和:

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]; 
}); 
+0

作品。謝謝。 I'm締結LLVM後端爲WASM仍然是WIP)另一種看法:如果從問題wasm2wast字節,然後wast2wasm結果你得到一個不同的和更小的字節碼。 wabt應該是一對一的。是? – noontz

+0

是的,WebAssembly LLVM後端仍然是WIP,但應該是主要功能。導出內存似乎是應該起作用的東西。你應該提交一個錯誤。 –