gpt4 book ai didi

rust - repr(C) 类型如何处理选项?

转载 作者:行者123 更新时间:2023-11-29 08:04:00 24 4
gpt4 key购买 nike

我有这个 C 代码:

typedef void (*f_t)(int a);

struct Foo {
f_t f;
};

extern void f(struct Foo *);

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)>,
}

我不明白为什么 Option 在这里。显然,Rust enum 和 C 指针在位级别上不是一回事,那么 Rust 编译器如何处理呢?

当我调用 C f 函数并将指针传递给 Rust 结构 Foo 时,编译器是否将 Foo_rust 转换为 Foo_C 然后只传递一个指向Foo_C 的指针给f?

最佳答案

来自 The Rust Programming Language chapter on FFI (强调我的):

Certain types are defined to not be null. This includes references (&T, &mut T), boxes (Box<T>), and function pointers (extern "abi" fn()). When interfacing with C, pointers that might be null are often used. 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.

换句话说:

Obviously that Rust enum and C pointer are not the same thing on the bit level

它们实际上是,当 Option包含一组特定的类型。


另见:

关于rust - repr(C) 类型如何处理选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com