Structs and Memory Layout
To interoperate with C structs, Cangjie uses struct decorated with @C as the correspondence. The struct's field order, types, and memory layout must exactly match the C-side definition—this is the foundation for passing data across language boundaries.
Structs decorated with @C automatically satisfy the CType constraint and can serve as parameters or return values for FFI functions. However, such structs have strict restrictions: member types must satisfy the CType constraint, cannot implement interfaces, cannot be used as enum associated value types, cannot be captured by closures, and cannot have generic parameters.
Through CPointer<T>, struct pointers can be passed across FFI boundaries, combined with write() and read() methods for read/write operations. Cangjie also provides sizeOf<T>() and alignOf<T>() functions to query a type's size and alignment values, which are very useful when manually managing memory.
@C struct must strictly match the C definition, otherwise it will cause memory layout misalignment and data corruption.Run the code on the right and observe the size output of Point and Rect structs to understand the memory footprint of different types.