digitalmars.D.learn - Struct size
- Lars T. Kyllingstad (14/14) Apr 19 2014 Say I have two structs, defined like this:
- Andrej Mitrovic via Digitalmars-d-learn (9/13) Apr 19 2014 The best thing to do is add a static assert and then you can relax:
- Lars T. Kyllingstad (15/26) Apr 19 2014 That's what I've done, but it would be nice to know the code
Say I have two structs, defined like this: struct A { /* could contain whatever */ } struct B { A a; } My question is, is it now guaranteed that A.sizeof==B.sizeof, regardless of how A is defined (member variable types, alignment, etc.)? More to the point, say I have a function foo() which looks like this: extern(C) void foo(A* ptr, size_t len); Is it now guaranteed that I can safely pass it a pointer to an array of Bs? That is, auto arr = new B[10]; foo(cast(A*) arr.ptr, arr.length); Thanks, Lars
Apr 19 2014
On 4/19/14, Lars T. Kyllingstad via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> wrote:Say I have two structs, defined like this: struct A { /* could contain whatever */ } struct B { A a; } My question is, is it now guaranteed that A.sizeof==B.sizeof?The best thing to do is add a static assert and then you can relax: ----- struct A { } struct B { A a; } static assert(A.sizeof == B.sizeof); ----- As for the ABI, I don't think I've ever seen it mentioned anywhere.
Apr 19 2014
On Saturday, 19 April 2014 at 12:26:16 UTC, Andrej Mitrovic via Digitalmars-d-learn wrote:On 4/19/14, Lars T. Kyllingstad via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> wrote:That's what I've done, but it would be nice to know the code won't break due to some combination of platform and/or compiler switches I didn't think to test. Anyway, I've played around a bit, and found that a combination of struct and field alignment *can* break my assumption: align(1) struct A { char c; align(1) int i; } struct B { A a; } Now, A.sizeof is 5, while B.sizeof is 8. I'd have to add align(1) to the declaration of B to fix it.Say I have two structs, defined like this: struct A { /* could contain whatever */ } struct B { A a; } My question is, is it now guaranteed that A.sizeof==B.sizeof?The best thing to do is add a static assert and then you can relax:
Apr 19 2014