Below is my Rust and JavaScript code, which I made based on an example that calls C code from JavaScript with an array and an example that calls Rust functions from JavaScript without parameters .
display-array.rs
#![feature(link_args)]
#[link_args = "-s EXPORTED_FUNCTIONS=['_display_array']"]
extern {}
#[no_mangle]
pub fn display_array(array: &[f32]) {
println!("Rust - array size: {}", array.len());
println!("Rust - array: {:?}", array);
}
fn main() {
}
callDisplayArray.js
var Module = require("./display-array.js");
display_array = Module.cwrap('display_array', 'number', ['number']);
var data = new Float32Array([1, 2, 3, 4, 5]);
var nDataBytes = data.length * data.BYTES_PER_ELEMENT;
var dataPtr = Module._malloc(nDataBytes);
var dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);
dataHeap.set(new Uint8Array(data.buffer));
console.log("Javascript - nDataBytes: " + nDataBytes + " , dataHeap.byteOffset: " + dataHeap.byteOffset + " , dataHeap: " + dataHeap);
display_array(dataHeap.byteOffset);
I successfully compiled the display-array.rs code into display-array.js by doing:
rustc --target asmjs-unknown-emscripten display-array.rs
I run my Javascript code with the command:
node callDisplayArray.js
Here are the debugging messages:
Javascript - nDataBytes: 20 , dataHeap.byteOffset: 5260840 , dataHeap: 0,0,128,63,0,0,0,64,0,0,64,64,0,0,128,64,0,0,160,64
Rust - array size: 0
Rust - array: []
The array in Rust is empty. I am new to Rust and Emscripten, so I'm really lost here. Perhaps I should not Module._mallocsay what it was when using C with Emscripten, and use something else instead?