2017-09-25 16 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.あなたによって提示された1つである:

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を読むことをお勧めします。

+1

注:C++ *の*もCのFFIを持っているので、そのCのコンパイラと互換性のあるC++のクラス/構造体は、RustからCのように使用できます。 –

+0

ありがとう@Shepmaster今コンパイルされます。それは働いているかもしれませんが、私のOctave helloworldはまだないので、私は100%確信していません。 https://github.com/ctaggart/octh_examples/blob/master/src/lib.rs –

+0

@CameronTaggartわかりませんが、すべての機能で名前のマングリングを防ぐ必要があります。 'Fhelloworld'に'#[no_mangle] 'がありませんか? –

関連する問題