[英]Why is returning None when of return type option<T> not return the null pointer when T is not a reference
The FFI section in the nomicon states that nomicon 中的 FFI 部分指出
The most common type that takes advantage of the nullable pointer optimization is
Option<T>
, whereNone
corresponds tonull
.利用可空指针优化的最常见类型是Option<T>
,其中None
对应于null
。 SoOption<extern "C" fn(c_int) -> c_int>
is a correct way to represent a nullable function pointer using the C ABI (corresponding to the C typeint (*)(int)
).因此Option<extern "C" fn(c_int) -> c_int>
是使用 C ABI 表示可空函数指针的正确方法(对应于 C 类型int (*)(int)
)。
However, this function does not return null
instead returning an address.但是,此函数不返回null
而是返回一个地址。
#[no_mangle]
pub extern "C" fn test() -> Option<u8> {
None
}
Rust also issues this warning : Rust 也会发出这个警告:
warning: `extern` fn uses type `Option<u8>`, which is not FFI-safe
--> src/lib.rs:2:29
|
2 | pub extern "C" fn test() -> Option<u8> {
| ^^^^^^^^^^ not FFI-safe
|
= note: `#[warn(improper_ctypes_definitions)]` on by default
= help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum
= note: enum has no representation hint
Changing the return type to Option<Box<u8>>
makes the function return null
as expected,将返回类型更改为Option<Box<u8>>
使函数按预期返回null
,
#[no_mangle]
pub extern "C" fn test2() -> Option<Box<u8>> {
None
}
The functions are called from c++ using the following header file使用以下头文件从 C++ 调用这些函数
extern "C" {
void * test();
void * test2();
}
The following c++ code下面的C++代码
int main()
{
cout << test() << endl;
cout << test2() << endl;
}
prints :印刷 :
0x5555a09d1200
0
nullable pointer optimization.可空指针优化。
If the Option
contains a pointer type, such as Box
then the optimisation can be applied.如果Option
包含指针类型,例如Box
则可以应用优化。 A u8
cannot be null and is not a pointer, but a Box<u8>
is an owned pointer to a u8
, so the optimisation works there. u8
不能为空并且不是指针,但Box<u8>
是指向u8
的拥有指针,因此优化在那里起作用。
More generally, this optimisation is called "niche-filling" which also applies to a few non-pointer Rust types, notably enums
.更一般地说,这种优化被称为“利基填充”,它也适用于一些非指针 Rust 类型,特别是enums
。 In the general case this is not safe for FFI though, and therefore doesn't apply to data in #[repr(C)]
structs except for pointer types.在一般情况下,这对 FFI 来说并不安全,因此不适用于#[repr(C)]
结构中的数据,指针类型除外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.