本文介绍了我如何将一个数组从JavaScript传递给已使用Emscripten编译的Rust?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我根据使用数组从JavaScript调用C代码的示例一个示例,该示例从JavaScript调用不带参数的Rust函数.

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:

I have succesfully compiled the display-array.rs code into display-array.js by running:

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

我使用以下命令运行Javascript代码:

I run my Javascript code with command:

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 ,而是使用其他名称?

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?

推荐答案

感谢您的帮助.我编辑了代码以使用 * const f32 ,现在可以打印数组的内容了:

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

这篇关于我如何将一个数组从JavaScript传递给已使用Emscripten编译的Rust?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:58