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

查看:290
本文介绍了如何在Rust for 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 just 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并将其转换为正确的类型.

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

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

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