通过一个C数组防锈功能 [英] Pass a C array to a Rust function
问题描述
我试图使防锈dylib和其他语言,如C,Python和其他人使用它。我已经成功地称为防锈功能了结和I32的说法从蟒蛇。现在,我想做一个功能,即带有一个数组(指针指向它,或任何必要通过一个数据集锈病LIB)。
I'm trying to make a Rust dylib and use it from other languages, like C, Python and others. I've successfully called a Rust function taking and i32 argument from python. Now I'm trying to make a function, that takes an array (pointer to it, or whatever necessary to pass a dataset to Rust lib).
#![crate_type = "dylib"]
#[no_mangle]
pub extern fn rust_multiply(size: i32, arrayPointer: &i32) -> i32
{
*(arrayPointer)
}
这正常工作。但
#![crate_type = "dylib"]
#[no_mangle]
pub extern fn rust_multiply(size: i32, arrayPointer: &i32) -> i32
{
*(arrayPointer + 1) // trying to get next element
}
失败
src/lib.rs:5:2: 6:2 error: type `i32` cannot be dereferenced
src/lib.rs:5 *(arrayPointer + 1)
src/lib.rs:6 }
另外这款:
pub extern fn rust_multiply(size: i32, array: &[i32]) -> i32
和做一些像数组[0]
失败,长度= 0的错误。
and doing something like array[0]
fails with "length = 0" error.
推荐答案
您必须作出一些努力为客户提供纯 C
API和使用不安全$ C $执行一些转换C。幸运的是,它不是那么难:
You have to make some efforts to provide pure C
api and implement some conversions using unsafe code. Fortunately, it is not so difficult:
extern crate libc;
#[no_mangle]
pub extern fn rust_multiply(size: libc::size_t, array_pointer: *const libc::uint32_t) -> libc::uint32_t {
internal_rust_multiply(unsafe { std::slice::from_raw_parts(array_pointer as *const i32, size as usize) }) as libc::uint32_t
}
fn internal_rust_multiply(array: &[i32]) -> i32
{
assert!(!array.is_empty());
array[0]
}
有是铁锈FFI 一个很好的介绍在官方网站。
这篇关于通过一个C数组防锈功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!