[英]How to create and return a C++ struct from Rust FFI?
I'm trying to create and return a C++ struct. 我正在尝试创建并返回C ++结构。 I am currently getting a
cannot move out of dereference of raw pointer
error when I try to compile. 当我尝试编译时,我当前
cannot move out of dereference of raw pointer
错误cannot move out of dereference of raw pointer
。 Any idea how I can make this work? 知道如何使这项工作有效吗?
#![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 ++结构
You cannot; 你不能; C++ (like Rust) does not have a stable, defined ABI.
C ++(如Rust)没有稳定的已定义ABI。 There is no way in Rust to specify that a structure has
repr(C++)
, therefore you cannot create such a structure, much less return it. 在Rust中无法指定结构具有
repr(C++)
,因此您不能创建这样的结构,更不用说返回它了。
The only stable ABI is the one presented by C. You can define structs as repr(C)
to be able to return them directly: 唯一稳定的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) }
}
That method is highly suspicious though; 但是,该方法非常可疑。 normally you'd see it as
通常你会看到
#[no_mangle]
pub extern "C" fn hello_world() -> ValueList {
unsafe {
let mut list = mem::uninitialized();
list_initialize(&mut list);
list
}
}
See also: 也可以看看:
I encourage you to read my Rust FFI Omnibus . 我鼓励您阅读我的Rust FFI Omnibus 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.