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

How to create and return a C++ struct from Rust FFI?

我正在尝试创建并返回C ++结构。 尝试编译时,当前出现cannot move out of dereference of raw pointer错误。 知道我如何进行这项工作吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#![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;
}

I'm trying to create and return a C++ struct

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

唯一稳定的ABI是C提出的。您可以将结构定义为repr(C)以便能够直接返回它们:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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) }
}

但是,该方法非常可疑。 通常你会看到

1
2
3
4
5
6
7
8
#[no_mangle]
pub extern"C" fn hello_world() -> ValueList {
    unsafe {
        let mut list = mem::uninitialized();
        list_initialize(&mut list);
        list
    }
}

也可以看看:

  • 当库使用模板(泛型)时,是否可以使用Rust的C ++库?

我鼓励您阅读我的Rust FFI Omnibus。