2017-09-25 9 views
2

저는 C++ 구조체를 만들고 반환하려고합니다. 컴파일을 시도 할 때 현재 cannot move out of dereference of raw pointer 오류가 발생합니다. 내가 어떻게이 일을 할 수 있는지 아는가?Rust FFI에서 C++ 구조체를 생성하고 반환하는 방법?

#![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; 
} 

답변

6

나는 당신은 할 수는 C++ 구조체

를 작성하고 반환하려고 해요; C++ (Rust와 같은)에는 안정적이고 정의 된 ABI가 없습니다. Rust에는 구조체에 repr(C++)이 있다는 것을 지정할 방법이 없으므로 구조체를 만들 수 없으며 반환 할 수 없습니다.

유일한 안정적인 ABI

는 직접 반환 할 수 repr(C)로 구조체를 정의 할 수 있습니다 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 
    } 
} 

참조로 볼 것 :


Is it possible to use a C++ library from Rust when the library uses templates (generics)?

+1

참고 : C++ * also *는 C FFI를 가지고 있으므로 C에서와 같이 모든 C++ 클래스/구조체가 Rust에서 사용할 수 있습니다. –

+0

Thanks @Shepmaster. 이제 컴파일됩니다. 그것은 효과가 있을지 모르지만, 내 Octave helloworld는 아직 아니므로 100 % 확실하지 않습니다. https://github.com/ctaggart/octh_examples/blob/master/src/lib.rs –

+0

@CameronTaggart 확실치는 않지만, 모든 기능에서 이름 맹 글링을 방지해야합니다. 'Fhelloworld'에'# [no_mangle]'가 없습니까? –