Rust FFI Wrapper types

Assuming I have the following (pure) Rust type:

pub struct Foo{
    bar: String,
    baz: Vec<i32>,

I want to pass this struct as an opaque pointer into an FFI. This means I'd need to annotate it either with #[repr(C)] or #[repr(transparent)] so that I can do stuff like

pub unsafe extern "C" fn create(path: *const c_char) -> *mut Foo;

pub unsafe extern "C" fn free(manager: *mut Foo);

However, that'd mean, I'd have to annotate all my pure rust types with FFI annotations. What'd I'm now asking myself: Is it possible to just create a Wrapper type and annotate that with the required attributes, i.e.

pub struct FooExtern(Foo);

Is this possible?

Foo doesn't need to have any particular repr if it is only being used as an opaque pointer by C. repr is only necessary if C is to use it by value, or access fields directly.

So if I just return a pointer to the struct and use free FFI functions taking that pointer, then no repr at all, correct?

Then, assuming I have a different struct that is not used as an opaque pointer, would the wrapper approach work, or would it be better to write a purpose FFI struct?


#[repr(transparent)] will just forward to the repr of the type it wraps, which if it wasn't specified, will be the default unstable #[repr(Rust)]. So no, the "wrapper" approach won't do anything, better to write a purpose-built struct.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.