Nasty supprise when using c 'anonymous struct and union' in D with 'static struct'

Steven Schveighoffer schveiguy at gmail.com
Tue Dec 29 17:49:20 UTC 2020


On 12/29/20 12:13 PM, Arjan wrote:
> On Tuesday, 29 December 2020 at 14:42:07 UTC, Steven Schveighoffer wrote:
>> On 12/29/20 7:38 AM, Arjan wrote:
>>> see https://en.cppreference.com/w/c/language/struct
>>>
>> I added in some printouts of the addresses of the variables.
>>
>> It appears that if you add static to the struct, it now becomes a 
>> static member of the union, which means it's not an instance variable, 
>> and is now a thread-local variable. Its address doesn't even coincide 
>> remotely with the address of v1.
>>
>> What is the equivalent behavior for C that you are expecting? The 
>> usage of "static struct" doesn't appear in that page you linked to.
> 
> On the C/C++ side there is no static. I added those on the D side to to 
> make sure there is no context pointer being added, since that will 
> change the layout and size of struct. (in the c/c++ code those unions 
> and structs are nested several levels deep)
> 
> Based on this: https://dlang.org/spec/struct.html#nested
> I expected to have the equivalent of C behavior in D by using the static 
> keyword, which in this case just caused havoc. So the other way around.
> 

structs only add context pointers if nested in functions (and even then, 
only if it's not POD). If nested in structs, classes, or unions (or 
anything else), then no context pointer is added.

So the answer is, don't use static.

-Steve


More information about the Digitalmars-d-learn mailing list