How can I pass an array from JavaScript to Rust that has been compiled with Emscripten?

Deadly 提交于 2019-12-07 19:30:04

问题


Below is my Rust and JavaScript code that 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 have succesfully compiled the display-array.rs code into display-array.js by running:

rustc --target asmjs-unknown-emscripten display-array.rs

I run my Javascript code with command:

node callDisplayArray.js

Here are the debug 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'm new to both Rust and Emscripten so I'm really lost here. Perhaps I shouldn't be calling Module._malloc like it's called when using C with Emscripten, and instead use something else?


回答1:


Thank you for the help. I edited the code to use *const f32 and now I am able to print the contents of the array:

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)); }
    }
}


来源:https://stackoverflow.com/questions/44047230/how-can-i-pass-an-array-from-javascript-to-rust-that-has-been-compiled-with-emsc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!