[swift-users] C compatible structs

KS Sreeram ks at claylabs.com
Mon Aug 1 06:20:21 CDT 2016


Is it possible to declare Swift structs that have C compatible memory layout?

In the code below, Foo and Bar have different sizes in Swift and C. Is it possible to make the Swift structs have the same layout as their C counterparts?

// Swift

struct Foo {
    var x: Int32;
    var a: Int8;

struct Bar {
    var foo: Foo;
    var b: Int8;

print(sizeof(Foo)); // output: 5
print(sizeof(Bar)); // output: 6

// C

typedef struct {
    int x;
    char a;
} Foo;

typedef struct {
    Foo foo;
    char b;
} Bar;

int main() {
    printf("%lu\n", sizeof(Foo)); // output: 8
    printf("%lu\n", sizeof(Bar)); // output: 12
    return 0;

KS Sreeram

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160801/be6e103e/attachment.html>

More information about the swift-users mailing list