【发布时间】:2019-12-28 04:26:16
【问题描述】:
我需要在 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]>`
【问题讨论】:
-
你的数组在栈上。您必须使用矢量或框,否则,您将遇到终身问题。
-
@FrenchBoiethios 感谢您的评论。我更新了问题。任何提示我该如何解决这个问题?