将 C 数组传递给 Rust 函数 [英] Pass a C array to a Rust function

查看:61
本文介绍了将 C 数组传递给 Rust 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作 Rust dylib 并从其他语言(如 C、Python 和其他语言)中使用它.我已经成功地调用了一个 Rust 函数,它从 Python 中获取了一个 i32 参数.现在我正在尝试创建一个函数,该函数接受一个数组(或指向它的指针,或者任何将数据集传递给 Rust 所需的任何东西).

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 an i32 argument from Python. Now I'm trying to make a function that takes an array (or a pointer to it, or whatever is necessary to pass a dataset to Rust).

#![crate_type = "dylib"]
#[no_mangle]
pub extern "C" fn rust_multiply(size: i32, arrayPointer: &i32) -> i32 {
    *(arrayPointer)
}

这按预期工作.但是

#![crate_type = "dylib"]
#[no_mangle]
pub extern "C" fn rust_multiply(size: i32, arrayPointer: &i32) -> i32 {
    *(arrayPointer + 1) // trying to get next element
}

失败

error[E0614]: type `i32` cannot be dereferenced
 --> src/lib.rs:4:5
  |
4 |     *(arrayPointer + 1) // trying to get next element
  |     ^^^^^^^^^^^^^^^^^^^

这样做:

pub extern fn rust_multiply(size: i32, array: &[i32]) -> i32

并且执行诸如 array[0] 之类的操作失败并显示length = 0";错误.

and doing something like array[0] fails with "length = 0" error.

推荐答案

您必须努力提供纯 C API 并使用不安全的代码实现一些转换.幸运的是,这并不难:

You have to make some efforts to provide a pure C API and implement some conversions using unsafe code. Fortunately, it is not so difficult:

extern crate libc;

#[no_mangle]
pub extern "C" 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]
}

Rust FFI 有一个很好的介绍 官方网站.

There is a good introduction for Rust FFI on the official site.

这篇关于将 C 数组传递给 Rust 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆