我正在使用“ wasm32-未知-未知”目标来开发一个涉及Rust和WebAssembly的项目。使用此函数从我的Rust代码返回Vec<i32>
没问题:
#[no_mangle]
pub extern "C" fn calc_vector() -> usize {
unsafe {
vec_len = 0;
}
let mut data: Vec<i32> = Vec::new();
for i in 0..1000 {
data.push(i);
}
unsafe {
vec_len = data.len();
}
data.as_mut_ptr() as usize
}
这将返回一个偏移量,我从JS调用另一个函数来获取我的Vec
的长度。然后,我再次使用JavaScript构建Vector(知道i32
-> 4x uint8
):
let vec_addr = exports.calc_vector();
let vec_len = exports.get_vec_len();
while(arr.length < vec_len) {
let numberUint8 = new DataView(view.buffer, vec_addr, 4);
let number = numberUint8.getInt32(0, true);
arr.push(number)
// move to next value in vector
vec_addr += 4;
}
使用此方法,我想创建一个返回Vec<Vec<i32>>
的Rust函数,但是它根本无法工作:
#[no_mangle]
pub extern "C" fn calc_vector_in_vector() -> usize {
unsafe {
vec_len = 0;
elements_in_vect = 0;
}
let mut outer_vec: Vec<*mut i32> = Vec::new();
let mut inner_vec: Vec<i32> = Vec::new();
for i in 0..100 {
inner_vec.push(i);
unsafe {
elements_in_vect += 1;
}
}
outer_vec.push(inner_vec.as_mut_ptr());
unsafe {
vec_len = outer_vec.len();
}
outer_vec.as_mut_ptr() as usize
}
我认为我可以使用与单个Vec
相同的逻辑:从calc_vector_in_vector()
返回的地址是外部向量的第一项,其地址为i32
内部向量的第一个元素的个数(实际数字)。但是,在这个地址上似乎是胡说八道。我在这里做错了什么?
答案 0 :(得分:0)
Because the vectors in my vector are all the same length, I can use the lazy_static crate to initialize a static Vec
wrapped in a Mutex
(to be able to alter it later on). LEN_VEC
is the length of the vector and SIZE_INNER_VEC
the size of one vector in my static vector.
I then add i32
to the static vector and return the address of the Vec
using ARRAY.lock().unwrap().as_mut_ptr() as usize
. With SIZE_INNER_VEC
and LEN_VEC
, I can recreate the vectors in my vector in JavaScript.
static mut LEN_VEC: usize = 0;
static mut SIZE_INNER_VEC: usize = 0;
lazy_static! {
// Wrap in Mutex to change later on
static ref ARRAY: Mutex<Vec<i32>> = Mutex::new(vec![]);
}
pub fn vector_in_vector() -> usize {
//set LEN_VEC
//set SIZE_INNER_VEC
ARRAY.lock().unwrap().as_mut_ptr() as usize
}