Swift and C structures in memory

Hello. In one code example I found next code in two files.
In first (One.swift)

private struct Vertex {
    var position: SIMD4<Float>
    var color: SIMD4<Float>
}

In second (Two.metal)

struct Vertex {
float4 position [[position]];
float4 color;
};

vertex Vertex main_vertex(device Vertex* vertices [[buffer(0)]], uint vid [[vertex_id]]) {
return vertices[vid];
}

So is it true that in memory these structures have same layout, and if we declare properties with same types and order it will work guaranteed?

C structs don't have to have the same layout as swift structs, for example https://godbolt.org/z/pfdaj4

If you want to have a struct with a C memory layout, the solution is to write it in C and import it using a bridging header

Thanks. I assemble an app via SPM and there is no way to mix Swift and Obj-C in one package as I know. So I will research a MTLBuffer and hope that data will match.

Also similar topic about the layout of data. Essentially there’s little one can say about the memory layout.

2 Likes