[英]How does a repr(C) type handle Option?
I have this C code: 我有这个C代码:
typedef void (*f_t)(int a);
struct Foo {
f_t f;
};
extern void f(struct Foo *);
bindgen generates the following Rust code (I have removed unimportant details): bindgen生成以下Rust代码(我已经删除了不重要的细节):
#[repr(C)]
#[derive(Copy, Clone)]
#[derive(Debug)]
pub struct Foo {
pub f: ::std::option::Option<extern "C" fn(a: ::std::os::raw::c_int)>,
}
I do not understand why Option
is here. 我不明白为什么
Option
在这里。 Obviously that Rust enum
and C pointer are not the same thing on the bit level, so how does the Rust compiler handle this? 显然,Rust
enum
和C指针在位级别上是不同的,那么Rust编译器如何处理呢?
When I call the C f
function and pass a pointer to a Rust struct Foo
, does the compiler convert Foo_rust
to Foo_C
and then only pass a pointer to Foo_C
to f
? 当我调用C
f
函数并将指针传递给Rust结构Foo
,编译器是否将Foo_rust
转换为Foo_C
,然后仅将指向Foo_C
的指针Foo_C
给f
?
From The Rust Programming Language chapter on FFI (emphasis mine): 从关于FFI (重点是我的) 的Rust编程语言一章 :
Certain types are defined to not be null.
某些类型定义为不为null。 This includes references (
&T
,&mut T
), boxes (Box<T>
), and function pointers (extern "abi" fn()
).这包括引用(
&T
,&mut T
),框(Box<T>
)和函数指针(extern "abi" fn()
)。 When interfacing with C, pointers that might be null are often used.与C接口时,经常使用可能为null的指针。 As a special case, a generic enum that contains exactly two variants, one of which contains no data and the other containing a single field, is eligible for the "nullable pointer optimization".
作为一种特殊情况,一个通用枚举恰好包含两个变体,其中一个不包含数据,另一个不包含单个字段,则可以使用“空指针优化”。 When such an enum is instantiated with one of the non-nullable types, it is represented as a single pointer, and the non-data variant is represented as the null pointer.
当使用非空类型之一实例化此类枚举时,它表示为单个指针,非数据变量表示为空指针。 So
Option<extern "C" fn(c_int) -> c_int>
is how one represents a nullable function pointer using the C ABI.因此,
Option<extern "C" fn(c_int) -> c_int>
是如何使用C ABI表示可为空的函数指针。
Said another way: 换句话说:
Obviously that Rust enum and C pointer are not the same thing on the bit level
显然,Rust枚举和C指针在位级别上是不同的
They actually are, when the Option
contains a specific set of types. 当
Option
包含一组特定类型时,它们实际上就是。
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.