如何在 Rust 中表示指向 C 数组的指针?
How to represent a pointer to a C array in Rust?
我需要一个 extern "C"
Rust 中的 FFI 函数并且想要接受一个固定大小的数组。 C 代码传递类似:
// C code
extern int(*)[4] call_rust_funct(unsigned char (*)[3]);
....
unsigned char a[] = { 11, 255, 212 };
int(*p)[4] = call_rust_funct(&a);
如何为它编写我的 Rust 函数?
// Pseudo code - DOESN'T COMPILE
pub unsafe extern "C" fn call_rust_funct(_p: *mut u8[3]) -> *mut i32[4] {
Box::into_raw(Box::new([99i32; 4]))
}
您需要对固定大小的数组使用 Rust 语法:
pub unsafe extern "C" fn call_rust_funct(_p: *mut [u8; 3]) -> *mut [i32; 4] {
Box::into_raw(Box::new([99i32; 4]))
}
您也可以随时使用 *mut std::os::raw::c_void
并将其转换为正确的类型。
我需要一个 extern "C"
Rust 中的 FFI 函数并且想要接受一个固定大小的数组。 C 代码传递类似:
// C code
extern int(*)[4] call_rust_funct(unsigned char (*)[3]);
....
unsigned char a[] = { 11, 255, 212 };
int(*p)[4] = call_rust_funct(&a);
如何为它编写我的 Rust 函数?
// Pseudo code - DOESN'T COMPILE
pub unsafe extern "C" fn call_rust_funct(_p: *mut u8[3]) -> *mut i32[4] {
Box::into_raw(Box::new([99i32; 4]))
}
您需要对固定大小的数组使用 Rust 语法:
pub unsafe extern "C" fn call_rust_funct(_p: *mut [u8; 3]) -> *mut [i32; 4] {
Box::into_raw(Box::new([99i32; 4]))
}
您也可以随时使用 *mut std::os::raw::c_void
并将其转换为正确的类型。