There is a combination of several FFI concepts in your answer, so first let me recommend that you read the Link .
There are two ways to achieve the desired result:
- use POD
struct(Plain Old Data) as well as a C-compatible structure - use an opaque pointer (
void*in C)
Mixing them, like you, does not make sense.
What to choose?
, .
, : . :
, POD , , Rust.
POD?
, , !
:
#[repr(C)]
pub struct RustStruct {
num: i32,
// other members, also PODs!
}
++
struct RustStruct {
int32_t num;
};
class Wrapper {
public:
private:
RustStruct rustStruct;
};
, stricto censu , ++:
class RustStruct {
public:
private:
int32_t num;
};
virtual.
?
:
, Rust:
#![feature(box_raw, box_syntax)]
use std::boxed;
pub struct RustStruct {
num: i32,
// other members, anything goes
}
pub extern "C" fn createRustStruct() -> *mut RustStruct {
boxed::into_raw(box RustStruct::new())
}
pub extern "C" fn destroyRustStruct(o: *mut RustStruct) {
boxed::from_raw(o);
}
... ++:
struct RustStruct;
RustStruct* createRustStruct();
void destroyRustStruct(RustStruct*);
class Wrapper {
public:
Wrapper(): rustStruct(RustStructPtr(createRustStruct())) {}
private:
struct Deleter {
void operator()(RustStruct* rs) const {
destroyRustStruct(rs);
}
};
typedef std::unique_ptr<RustStruct, Deleter> RustStructPtr;
RustStructPtr rustStruct;
};
, , , Wrapper ( Rust). , !
. , ++, copy/destroy , .