将C++异常映射到Result

Ale*_*kiy 4 c++ opencv ffi rust

我正在编写一个Rust库,它是C++库的包装器.

这是C++方面:

#define Result(type,name) typedef struct { type value; const char* message; } name

extern "C" 
{
    Result(double, ResultDouble);

    ResultDouble myFunc() 
    {
        try
        {
            return ResultDouble{value: cv::someOpenCvMethod(), message: nullptr};
        }
        catch( cv::Exception& e )
        {
            const char* err_msg = e.what();
            return ResultDouble{value: 0, message: err_msg};
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和相应的Rust方面:

#[repr(C)]
struct CResult<T> {
    value: T,
    message: *mut c_char,
}

extern "C" {
    fn myFunc() -> CResult<c_double>;
}

pub fn my_func() -> Result<f64, Cow<'static, str>> {
    let result = unsafe { myFunc() };
    if result.message.is_null() {
        Ok(result.value)
    } else {
        unsafe {
            let str = std::ffi::CString::from_raw(result.message);
            let err = match str.into_string() {
                Ok(message) => message.into(),
                _ => "Unknown error".into(),
            };
            Err(err)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我这里有两个问题:

  1. *const char在C++方面使用但是*mut c_char在Rust上可以吗?我需要它,因为CString::from_raw需要可变参考.
  2. 我应该用CStr吗?如果是的话,我该如何管理它的生命周期?我应该释放这个记忆还是它有静态的生命?

通常我只想映射一个C++异常,它发生在对Rust的FFI调用中 Result<T,E>

这样做的惯用方法是什么?

E_n*_*ate 7

  1. 我可以在C++端使用*const char但在Rust上使用*mut c_char吗?我需要它,因为CString :: from_raw需要可变引用.

关于CString::from_raw问题的第一部分的文件已经回答:

"这应该只使用之前通过调用in_raw获得的指针来调用CString".

尝试使用指向未创建的字符串的指针在CString这里是不合适的,并且会吃掉你的洗衣服.

  1. 我应该使用CStr吗?如果是的话,我该如何管理它的生命周期?我应该释放这个记忆还是它有静态的生命?

如果保证返回的C风格的字符串具有静态生命周期(例如,它具有静态持续时间),那么您可以&'static CStr从中创建一个并返回它.但是,情况并非如此:cv::Exception包含多个成员,其中一些成员拥有字符串对象.一旦程序离开了范围myFunc,被捕获的异常对象e就会被销毁,因此,来自的任何东西what()都会失效.

        const char* err_msg = e.what();
        return ResultDouble{0, err_msg}; // oops! a dangling pointer is returned
Run Code Online (Sandbox Code Playgroud)

虽然可以跨FFI边界传输值,但所有权的责任应始终保持在该值的来源.换句话说,如果C++代码正在创建异常并且我们想要将这些信息提供给Rust代码,那么C++代码必须保留该值并最终将其释放.我冒昧地选择了下面一种可能的方法.

通过关于复制C字符串的这个问题,我们可以重新实现myFunc将字符串存储在动态分配的数组中:

#include <cstring>

ResultDouble myFunc() 
{
    try
    {
        return ResultDouble{value: cv::someOpenCvMethod(), message: nullptr};
    }
    catch( cv::Exception& e )
    {
        const char* err_msg = e.what();
        auto len = std::strlen(err_msg);
        auto retained_err = new char[len + 1];
        std::strcpy(retained_err, err_msg);
        return ResultDouble{value: 0, message: retained_err};
    }
}
Run Code Online (Sandbox Code Playgroud)

这使得我们返回一个指向有效内存的指针.然后,必须公开一个新的公共函数来释放结果:

// in extern "C"
void free_result(ResultDouble* res) {
    delete[] res->message;
}
Run Code Online (Sandbox Code Playgroud)

在Rust-land中,我们将使用此问题中描述的方法保留相同字符串的副本.一旦完成,我们不再需要内容result,因此可以通过FFI函数调用来释放它free_result.处理的结果to_str(),而不unwrap留给作为练习读者.

extern "C" {
    fn myFunc() -> CResult<c_double>;
    fn free_result(res: *mut CResult<c_double>);
}

pub fn my_func() -> Result<f64, String> {
    let result = unsafe {
        myFunc()
    };
    if result.message.is_null() {
        Ok(result.value)
    } else {
        unsafe {
            let s = std::ffi::CStr::from_ptr(result.message);
            let str_slice: &str = c_str.to_str().unwrap();
            free_result(&mut result);
            Err(str_slice.to_owned())
        }
    }
}
Run Code Online (Sandbox Code Playgroud)