如何在Rust中表示一个指向C数组的指针? [英] How to represent a pointer to a C array in Rust?

查看:115
本文介绍了如何在Rust中表示一个指向C数组的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rust中需要一个 extern"C" FFI函数,并希望接受一个固定大小的数组.C代码传递如下内容:

I need an extern "C" FFI function in Rust and want to accept an array of fixed size. The C code passes something like:

// 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函数?

How do I write my Rust function for it ?

// 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的语法:

You need to use Rust's syntax for fixed size arrays:

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 并将其转换为正确的类型.

You can also always use *mut std::os::raw::c_void and transmute it to the correct type.

这篇关于如何在Rust中表示一个指向C数组的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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