如何从Rust FFI创建和返回C++结构?

Cam*_*art 2 ffi rust

我正在尝试创建并返回一个C++结构.我在cannot move out of dereference of raw pointer尝试编译时遇到错误.知道如何让这个工作吗?

#![allow(non_snake_case)]
#![allow(unused_variables)]

extern crate octh;

// https://thefullsnack.com/en/string-ffi-rust.html
use std::ffi::CString;

#[no_mangle]
pub unsafe extern "C" fn Ghelloworld(
    shl: *const octh::root::octave::dynamic_library,
    relative: bool,
) -> *mut octh::root::octave_dld_function {
    let name = CString::new("helloworld").unwrap();
    let pname = name.as_ptr() as *const octh::root::std::string;
    std::mem::forget(pname);

    let doc = CString::new("Hello World Help String").unwrap();
    let pdoc = doc.as_ptr() as *const octh::root::std::string;
    std::mem::forget(pdoc);

    return octh::root::octave_dld_function_create(Some(Fhelloworld), shl, pname, pdoc);
}

pub unsafe extern "C" fn Fhelloworld(
    args: *const octh::root::octave_value_list,
    nargout: ::std::os::raw::c_int,
) -> octh::root::octave_value_list {
    let list: *mut octh::root::octave_value_list = ::std::ptr::null_mut();
    octh::root::octave_value_list_new(list);
    std::mem::forget(list);
    return *list;
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 6

我正在尝试创建并返回一个C++结构

你不能; C++(如Rust)没有稳定的,定义的ABI.在Rust中没有办法指定一个结构repr(C++),因此你不能创建这样的结构,更不用说返回它了.

唯一稳定的ABI是由C表示的.您可以定义结构repr(C)以便能够直接返回它们:

extern crate libc;

use std::ptr;

#[repr(C)]
pub struct ValueList {
    id: libc::int32_t,
}

#[no_mangle]
pub extern "C" fn hello_world() -> ValueList {
    let list_ptr = ::std::ptr::null_mut();
    // untested, will cause segfault unless list_ptr is set
    unsafe { ptr::read(list_ptr) }
}
Run Code Online (Sandbox Code Playgroud)

但这种方法非常可疑; 通常你会看到它

#[no_mangle]
pub extern "C" fn hello_world() -> ValueList {
    unsafe {
        let mut list = mem::uninitialized();
        list_initialize(&mut list);
        list
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


我鼓励你阅读我的Rust FFI Omnibus.

  • 注意:C++ *也* 有一个 C FFI,因此任何与其对应的 C 兼容的 C++ 类/结构都可以从 Rust 中使用,就像从 C 中一样。 (3认同)