data: Wasm definition
The data definition defines a segment of bytes that can be copied into linear memory.
Try it
(module
(memory (export "memory") 1)
(data $greeting1 (i32.const 0) "Hello ")
(data $greeting2 "World")
(func (export "init")
i32.const 6 ;; destination offset in memory
i32.const 0 ;; offset into the data segment
i32.const 5 ;; number of bytes to copy
memory.init $greeting2
)
)
WebAssembly.instantiateStreaming(fetch("{%wasm-url%}")).then((result) => {
result.instance.exports.init();
const memBuffer = result.instance.exports.memory.buffer;
const memArray = new Uint8Array(memBuffer, 0, 11);
console.log(new TextDecoder().decode(memArray));
});
In the above example, we specify two data definitions with identifiers $greeting1 and $greeting2, containing the strings "Hello " and "World", respectively. The first data definition has a memory offset specified ((i32.const 0)), so immediately writes the string to the specified memory at bytes 0–4. The second data definition doesn't have a memory offset specified, so isn't written to memory until the memory.init instruction is executed later on.
In the JavaScript, we call the exported init() function to write the second data definition into memory, then decode the exported memory buffer and log the result ot the console.
Syntax
;; Active form, written to memory immediately data name memory_index offset data_string ;; Passive form, written later via memory.init data name data_string
data-
The
datadefinition type. Must always be included first. nameOptional-
An optional identifying name for the table. This must begin with a
$symbol, for example$my_table. If this is omitted, thedatacan be identified (for example when callingmemory.init) by its index, for example0for the firstdatain the wasm script,1for the second, etc. memory_indexOptional-
An integer representing the index number of the
memoryinstance to write the data to, in the case of Wasm modules with multiple memories. offsetOptional-
An integer representing the offset at which to start writing the data in the
memory. data_string-
A string of literal bytes defining the data represented by this
datainstance.
Specifications
This feature does not appear to be defined in any specification.>Browser compatibility
See also
memorydefinition- WebAssembly memory instructions