gpt4 book ai didi

rust - 使用闭包从 Option<&T> 获取原始指针是否安全?

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

我有一个 Option<&T>我想要一个原始的 *const T如果选项为 None,则为 null .我想包装一个 FFI 调用,它接受一个指向 Rust 分配的对象的指针。

此外,我使用的 FFI 接口(interface)具有借用语义(我分配一些东西并传入指向它的指针),而不是所有权语义

extern "C" {
// Parameter may be null
fn ffi_call(*const T);
}

fn safe_wrapper(opt: Option<&T>) {
let ptr: *const T = ???;
unsafe { ffi_call(ptr) }
}

我可以使用 match语句来执行此操作,但该方法感觉非常冗长。

let ptr = match opt {
Some(inner) => inner as *const T,
None => null(),
};

我还可以将引用映射到指针,然后使用 unwrap_or .

let ptr = opt.map(|inner| inner as *const T).unwrap_or(null());

但是,我担心指针在通过闭包时可能会失效。 Rust 是否保证最终指针将指向与原始引用相同的东西?如果TCopy ,这是否以有意义的方式改变了语义?有没有我忽略的更好方法?

最佳答案

是的,这是安全的。我会写成:

use std::ptr;

fn safe_wrapper(opt: Option<&u8>) {
let p = opt.map_or_else(ptr::null, |x| x);
unsafe { ffi_call(p) }
}

如果您发现自己写了很多这样的东西,您可以将它变成一个特征并将其减少到一个方法调用。

the pointer might be invalidated as it passes through the closure

可能是,如果您自己以某种方式使它无效。因为该函数采用引用,所以您可以确定所引用的值在函数调用期间有效——这就是 Rust 的借用检查器的目的。

指针变为无效的唯一方法是更改​​指针的值(例如,向其添加偏移量)。既然您不这样做,那也没关系。

Does Rust make a guarantee that the final pointer will point to the same thing as the original reference?

这取决于你所说的“最终”是什么意思。将引用转换为指针将始终导致两个值在内存中包含相同的位置。其他任何东西都是故意恶意的,没有人会一开始就使用 Rust。

If T is Copy, does this change the semantics in a meaningful way?

没有。此外,我们正在谈论一个&T,它是always Copy

另见:


the FFI interface I am using has borrowing semantics (I allocate something and pass in a pointer to it), not ownership semantics

需要明确的是,您不能仅根据函数类型来确定所有权。

此 C 函数取得所有权:

void string_free(char *)

这个 C 函数借用了:

size_t string_len(char *)

两者都带一个指针。 Rust 通过清楚地描述什么是借用和什么是所有权转移来改善这种情况。

extern "C" {
// Parameter may be null
fn ffi_call(*const T);
}

这段代码毫无意义;它没有定义泛型类型 T 并且 FFI 函数无论如何都不能有泛型类型。

关于rust - 使用闭包从 Option<&T> 获取原始指针是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320663/

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