rust - 如何将值的所有权从 Rust 转移到 C 代码?

标签 rust ffi ownership

我正在尝试使用 FFI 编写一些 Rust 代码,其中涉及 C 获取结构的所有权:

fn some_function() {
    let c = SomeStruct::new();
    unsafe {
        c_function(&mut c);
    }
}

我希望 c_function 获得 c 的所有权。在 C++ 中,这可以通过 unqiue_ptrrelease 方法来实现。 Rust 中有类似的东西吗?

最佳答案

C++中的std::unique_ptr类型对应Rust中的Box.release() corresponds to Box::into_raw .

let c = Box::new(SomeStruct::new());
unsafe {
    c_function(Box::into_raw(c));
}

请注意,C 函数应将指针的所有权返回给 Rust 以销毁结构。使用 C 的 free 或 C++ 的 delete 释放内存是不正确的。

pub unsafe extern "C" fn delete_some_struct(ptr: *mut SomeStruct) {
    // Convert the pointer back into a Box and drop the Box.
    Box::from_raw(ptr);
}

关于rust - 如何将值的所有权从 Rust 转移到 C 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42523354/

相关文章:

types - 具有泛型类型的多个特征的类型别名

python - 在 Python 中取消引用 FFI 指针以获取底层数组

rust - 如何将指向自身的指针传递给 C++ 以便它可以执行回调?

vector - 如何将一个 Vec 传递给 Rust 中的多个函数?

struct - 如何在不出现 "use moved value"错误的情况下绑定(bind)盒装结构的多个字段?

rust - Rayon 无法将 .chars() 迭代器转换为 .par_iter()

json - 写入 JSON 文件时如何转义 PathBuf 变量中的反斜杠字符?

python - 构建 ctypes 类的简洁方式

haskell - 从 Haskell 调用 Clojure 函数

rust - 如何借用一个展开的 Option<T>?