我的.wat
文件包含以下2行代码。
(memory $buf 1)
(data (i32.const 0) "hello")
我想将$buf
作为参数传递给导入的Javascript函数。 Javascript端的代码如下所示:
function consoleLogString(memory, offset,length){
var bytes = new Uint8Array(memory.buffer, 0, 5);
var string = new TextDecoder('utf8').decode(bytes);
console.log(string);
}
var importObj = {console : {log: consoleLogString}};
fetchAndInstantiate('stringLogger2.wasm',importObj).then(function(instance) {
instance.exports.writeHi();
});
}
在沉重的一面,我希望能够做类似
的事情(import "console" "log" (func $log (param i32 i32 i32)))
(export "writeHi" (func $writeHi))
(memory $buf 1)
(data (i32.const 0) "hello")
(func $writeHi
;; how do I push my buffer onto the stack so it can be passed to the function?
i32.const 0
i32.const 5
call $log
)
答案 0 :(得分:0)
据我所知,WebAssembly仅支持i32 / i64 / f32 / f64,因此这意味着您无法传入指针。
Pass a JavaScript array as argument to a WebAssembly function
但您可以将 内存 导入到wasm实例,并且可以将日志功能与导入的 内存
function consoleLogString(memory, offset, length) {
var bytes = new Uint8Array(memory.buffer, offset, length);
var string = new TextDecoder('utf8').decode(bytes);
console.log(string);
}
const memory = new WebAssembly.Memory({ initial: 2 });
const consoleLogStringWrapper = memory => (offset, length) => consoleLogString(memory, offset, length);
var importObj = {
imp : {
mem: memory,
log: consoleLogStringWrapper(memory)
}
};
fetchAndInstantiate('stringLogger2.wasm', importObj).then(function(instance) {
instance.exports.writeHi();
});
你的观察将与此类似:
(module
(import "imp" "log" (func $log (param i32 i32)))
(memory (import "imp" "mem") 1)
(func $writeHi
i32.const 0
i32.const 5
call $log
)
(data (i32.const 0) "hello")
(export "writeHi" (func $writeHi))
)
使用以下js在wat2wasm上进行测试:
function consoleLogString(memory, offset, length) {
var bytes = new Uint8Array(memory.buffer, offset, length);
var string = new TextDecoder('utf8').decode(bytes);
console.log(string);
}
const memory = new WebAssembly.Memory({ initial: 2 });
const consoleLogStringWrapper = memory => (offset, length) => consoleLogString(memory, offset, length);
var importObj = {
imp : {
mem: memory,
log: consoleLogStringWrapper(memory)
}
};
const wasmInstance = new WebAssembly.Instance(wasmModule, importObj);
const { writeHi } = wasmInstance.exports;
writeHi();