gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:02:54 24 4
gpt4 key购买 nike

我正在尝试创建并返回一个 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;
}

最佳答案

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

你不能; 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) }
}

不过这种方法非常可疑;通常你会把它看作

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

另见:


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

关于rust - 如何从 Rust FFI 创建和返回 C++ 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com