I have a struct:
struct A {
names: Vec<String>,
}
And another struct:
#[repr(C)]
struct B {
pub a: A,
}
Does this make A
also have the repr(C)
annotation? Would it be correct to pass such structure to C code ?
Your answers are:
#[repr(C)]
doesn't make structures "safe to FFI", it guarantees that the in-memory representation will be as is and the compiler will not try to optimize them for space/efficiency under the cover. This is accidentally what is also needed for safe FFI.
It certainly isn't safe to pass your structure to C code. There are some caveats in the documentation , including:
DSTs, tuples, and tagged unions are not a concept in C and as such are never FFI safe
You have no guarantee about whether any of these are in the Vec
. Also, since Vec
is opaque.
If the type would have any drop flags, they will still be added"
Again, Vec
may have some.
And in any case, for it to make any sense at the receiving C code, you need to declare your struct in C as well; and since Vec<String>
is opaque, there isn't a reasonable way to do so.
I think the reason for having #[repr(C)]
is to reproduce data to match an existing C API you want to interoperate with; not to somehow directly expose internal Rust types to C.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.