Reputation: 5936
In the WebAssembly text format, every data
expression I've seen provides data as a string, as in "hello"
. But the spec says that the last argument of data
can be a concat((𝑏*)*)
, which apparently represents a concatenation of data elements.
Does anyone have an example of this? I can't find anything helpful. Thanks.
Upvotes: 0
Views: 123
Reputation: 36118
A data segment can be written with multiple strings, which are simply concatenated:
(data (offset (i32.const 0))
"... part 1 ..."
"... part 2 ..."
"... part 3 ..."
)
The only reason for this feature is to enable splitting the string over multiple lines (cf. string literals in C).
Upvotes: 3
Reputation: 560
As I understand spec in data
section last argument is size of current block. As data
uses linear memory possible
you can guess size of the string and return concat
of strings
(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))
)
with this 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();
will return hello world
, you can check on wat2wasm
Upvotes: 0