如何将数组从JavaScript传递给使用Emscripten编译的Rust?

时间:2017-05-18 12:03:05

标签: javascript rust emscripten

以下是我根据an example that calls C code from JavaScript with an arrayan example that calls Rust functions from JavaScript without parameters制作的Rust和JavaScript代码。

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

我通过运行成功将display-array.rs代码编译成display-array.js:

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

我使用命令运行我的Javascript代码:

node callDisplayArray.js

以下是调试消息:

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: []

Rust中的数组为空。我是Rust和Emscripten的新手,所以我真的迷失在这里。也许我不应该在使用C和Emscripten时调用Module._malloc,而是使用别的东西?

1 个答案:

答案 0 :(得分:0)

感谢您的帮助。我编辑了代码以使用*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)); }
    }
}