我需要编写一个函数,在 Rust 中返回一个 u16 整数数组。然后,这个函数应该被 FFI 使用。
但结果完全错误(期望:
extern crate libc;
use libc::{uint16_t};
#[no_mangle]
pub extern fn ffi_test() -> *const uint16_t {
let test: [u16;4] = [1,2,3,4];
test.as_ptr()
}
Rust的代码可以在没有错误的情况下编译。我使用Ruby来测试ffi调用:
# coding: utf-8
require 'ffi'
module MyMod
extend FFI::Library
ffi_lib 'my_ffi_test_lib'
attach_function :ffi_test, [], :pointer
end
a_ptr = MyMod.ffi_test
size = 4
result_array = a_ptr.read_array_of_uint16(size)
p result_array
但结果完全错误(期望:
[1, 2, 3, 4]
):$ ruby ffi_test.rb
[57871, 25191, 32767, 0]
好像我读取了完全不同的内存地址。我猜可能在 Rust 数组上不应该使用 #as_ptr()
?
编辑
根据 @FrenchBoiethios 的建议,我尝试对数组进行包装:
extern crate libc;
use libc::{uint16_t};
#[no_mangle]
pub extern fn ffi_test() -> *mut uint16_t {
let test: [u16;4] = [1,2,3,4];
let b = Box::new(test);
Box::into_raw(b)
}
这会导致编译错误:
note: expected type `std::boxed::Box<u16>`
found type `std::boxed::Box<[u16; 4]>`