我将数据从Rust传递给C.虽然传递原语似乎很容易,但我有点迷失结构.
我有以下Rust代码:
use ::std::os::raw::*;
static NAME: &[c_char] = &[65, 66, 67, 0];
#[repr(C)]
pub struct MyStruct {
pub x: c_int,
pub y: *const c_char,
}
#[no_mangle]
pub extern "C" fn get_my_struct() -> *const MyStruct {
let my_struct = MyStruct {
x: 11 as c_int,
y: NAME.as_ptr(),
};
unsafe {
::std::mem::transmute(Box::new(my_struct))
}
}
Run Code Online (Sandbox Code Playgroud)
以下C代码:
typedef struct _my_struct my_struct;
extern const my_struct get_my_struct(void);
struct _my_struct {
int x;
const char *y;
};
int main(void) {
my_struct my_complex_struct = get_my_struct();
return 0;
} …Run Code Online (Sandbox Code Playgroud)