Does repr(C) apply to the types of fields?

For example:

struct Foo {
    f1: i8,
    f2: i16,
    f3: i8,
}

#[repr(C)]
struct Bar {
    foo: Foo,
}

in this case, does Foo's layout also be the C representation? If not, How to deal with this problem (in my case the Foo type is not in my crate)?

As far as I can tell, no. You can look at the Rust reference.
Could you please tell why you'd need to do this for a type from another crate?

The reference only talks about how the fields layout in a struct, not saying (or not clear) how the filed's inner layout. At least the reference is not clear to me.

@psionic12, are you just trying to provide a thin, newtype wrapper around some other type from another library? If so, that's what repr(transparent) is for.

No, because the declaration of one type shouldn't globally affect the declaration of another type.

4 Likes

Rust makes no guarantees on the layout by default. If you need a fixed layout, then Foo would need repr(C).

No... I want every thing in the Bar type are represented in C, So I can put them into GPU.

This is really painful since I have to create a repr(C) version of data struct for very one in math libraries(vector, quaternion, matrix and so one)... Does anybody who also come across this problem?

This sounds like an XY problem. You might want to create a thread about the problem you're trying to solve. You may not need to recreate every struct with repr(C).

If the math library you are using doesn't already have #[repr(C)] on its types, consider sending it a suggestion or PR to do so — or switching to one that does. Your requirement is a common one.

1 Like

yeah, I found that crate nalgebra makes all the types repr(C), I'm going to use this one instead.

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.