如何将可以为空的原始指针转换为选项?

How to convert a raw pointer, which can be null, into an Option?

我写了下面的宏:

macro_rules! ptr_to_opt {
    ($p: expr) => {
        if $p.is_null() {
            None
        } else {
            Some($p)
        }
    };
}

这让我可以检查 match:

中的原始指针
match ptr_to_opt!(myRawPtr) {
    Some(ptr) => { ... },
    None      => { ... },
}

是否有任何内置功能可以替换我的 ptr_to_opt 宏?


编辑:

这个问题与的区别在于as_ref将指针转换为引用,而我想保留指针。

是的,您可以使用 NonNull::new to get an Option<NonNull<T>> from a *mut T. If you just want an Option<*mut T> (which you probably shouldn't need considering NonNull can do just about everything a pointer can), then you can map it with NonNull::as_ptr

所以5个月后,我找到了解决这个问题的两种不同方法。

首先:使用裸指针的as_mut方法。在Ok中返回的是引用而不是指针,但在某些情况下引用可以隐式转换为指针,因此它在某些情况下有效。

第二个:下面的函数:

use std::ffi::c_void;

pub fn ptr_as_opt(ptr: *mut c_void) -> Option<*mut c_void> {
    if ptr.is_null() {
        None
    } else {
        Some(ptr)
    }
}