How to pass an array from JavaScript to Rust that was compiled using Emscripten?

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() {
    /* Intentionally left blank */
}

callDisplayArray.js

var Module = require("./display-array.js");

// Import function from Emscripten generated file
display_array = Module.cwrap('display_array', 'number', ['number']);

var data = new Float32Array([1, 2, 3, 4, 5]);

// Get data byte size, allocate memory on Emscripten heap, and get pointer
var nDataBytes = data.length * data.BYTES_PER_ELEMENT;
var dataPtr = Module._malloc(nDataBytes);

// Copy data to Emscripten heap (directly accessed from Module.HEAPU8)
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?

+2
1

. *const f32, :

pub fn display_array(array_ptr: *const f32, array_length: isize) {
    for offset in 0..array_length {
        unsafe { println!("Rust - value in array: {:?}", *array_ptr.offset(offset)); }
    }
}
0

Source: https://habr.com/ru/post/1683871/


All Articles