Passing a Rust object through C code

Just a quick confirmation: I have a Rust object, that is created in Rust and used in Rust, but passed through C code in between. To transport it I have a struct that is defined as:

#[repr(C)]
struct MyStruct {
  my_obj: Box<MyObj>,
}

and on the C side of things:

struct MyStruct {
  void* my_obj,
}

There is a warning, that complains about improper_ctypes. Now I found std::boxed - Rust that basically says, this is ok, but there are caveats. I don't understand those entirely. So is this (always and guaranteed) correct and I can just mute the warning?

I believe this is correct, but it would be more obviously correct to use the type below when talking to C.

#[repr(C)]
struct MyStructC {
    my_obj: *const MyObj,
}
1 Like

Just to be clear, this is only fine if MyObj is Sized (i.e. not a trait object, etc). You need to also mark MyObj as repr(C) if you plan on accessing it from C or may want to use different versions of rustc for the two Rust halves

3 Likes

It's fine as long as MyObj is sized. You can even use it on the C size (but be careful to not change the pointer). However, if you only need it for Rust, it's preferred to an opaque type:

typedef const void* MyStructP;
1 Like