C compatible structs


(KS Sreeram) #1

Hello

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;
}

Best
KS Sreeram


(Dmitri Gribenko) #2

The only supported way to do this is to declare your structs in a C
header that you import in Swift as a module, and #include in your C
libraries.

Dmitri

···

On Mon, Aug 1, 2016 at 4:20 AM, KS Sreeram via swift-users <swift-users@swift.org> wrote:

Hello

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

--
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr@gmail.com>*/


(KS Sreeram) #3

It doesn’t. Swift uses a different layout than C. In the earlier example code, strideof(Bar) is 8 in Swift, whereas sizeof(Bar) is 12 in C.

Best
KS Sreeram

···

On 01-Aug-2016, at 5:17 PM, Chris McIntyre <nothingwasdelivered@gmail.com> wrote:

Swift's strideOf my give you what you want (I'm not at my Mac to test)


(Chris Lattner) #4

Right. In the future we will probably add the ability to put explicit alignment/layout information on structure fields. This would be useful for this, as well as other cases where you’re trying to match a specific layout used in an on-disk file format or memory mapped device. That said, this doesn’t fit in the scope for Swift 4 stage 1.

-Chris

···

On Aug 1, 2016, at 9:12 AM, Dmitri Gribenko via swift-users <swift-users@swift.org> wrote:

On Mon, Aug 1, 2016 at 4:20 AM, KS Sreeram via swift-users > <swift-users@swift.org> wrote:

Hello

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

The only supported way to do this is to declare your structs in a C
header that you import in Swift as a module, and #include in your C
libraries.


(KS Sreeram) #5

Right. In the future we will probably add the ability to put explicit alignment/layout information on structure fields. This would be useful for this, as well as other cases where you’re trying to match a specific layout used in an on-disk file format or memory mapped device.

That was exactly my use case. I’m storing raw structs in LMDB.

That said, this doesn’t fit in the scope for Swift 4 stage 1.

Though a bit cumbersome, Dmitri’s solution is good enough for now. It’ll be great to have this directly supported in Swift.

Thanks
KS Sreeram

···

On 03-Aug-2016, at 10:02 AM, Chris Lattner <clattner@apple.com> wrote: