在数据表达式中设置数据
Setting data in a data expression
在 WebAssembly 文本格式中,我见过的每个 data
表达式都以字符串形式提供数据,如 "hello"
。但是规范说 data
的最后一个参数可以是 concat((*)*)
,这显然表示数据元素的串联。
有没有人有这方面的例子?我找不到任何有用的东西。谢谢
据我所知,data
部分最后一个参数是当前块的大小。由于 data
使用 linear memory possible
您可以猜测字符串的大小和 return concat
的字符串
(module
(import "imp" "log" (func $log (param i32 i32)))
(memory (import "imp" "mem") 1)
(func $writeHi
i32.const 0
i32.const 13
call $log
)
(data (i32.const 0) "hello")
(data (i32.const 5) " ")
(data (i32.const 6) "world")
(export "writeLog" (func $writeHi))
)
用这个 js
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();
会returnhello world
,可以在wat2wasm
上查看
一个数据段可以写多个字符串,简单的拼接起来:
(data (offset (i32.const 0))
"... part 1 ..."
"... part 2 ..."
"... part 3 ..."
)
此功能的唯一原因是允许将字符串拆分为多行(参见 C 中的字符串文字)。
在 WebAssembly 文本格式中,我见过的每个 data
表达式都以字符串形式提供数据,如 "hello"
。但是规范说 data
的最后一个参数可以是 concat((*)*)
,这显然表示数据元素的串联。
有没有人有这方面的例子?我找不到任何有用的东西。谢谢
据我所知,data
部分最后一个参数是当前块的大小。由于 data
使用 linear memory possible
您可以猜测字符串的大小和 return concat
的字符串
(module
(import "imp" "log" (func $log (param i32 i32)))
(memory (import "imp" "mem") 1)
(func $writeHi
i32.const 0
i32.const 13
call $log
)
(data (i32.const 0) "hello")
(data (i32.const 5) " ")
(data (i32.const 6) "world")
(export "writeLog" (func $writeHi))
)
用这个 js
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();
会returnhello world
,可以在wat2wasm
一个数据段可以写多个字符串,简单的拼接起来:
(data (offset (i32.const 0))
"... part 1 ..."
"... part 2 ..."
"... part 3 ..."
)
此功能的唯一原因是允许将字符串拆分为多行(参见 C 中的字符串文字)。