How to fix the mismatch struct size

Arjan arjan at ask.me.to
Tue May 17 19:52:23 UTC 2022


On Tuesday, 17 May 2022 at 09:40:40 UTC, test123 wrote:
> On Monday, 16 May 2022 at 15:28:42 UTC, Arjan wrote:
>>
>> - enforce in C/C++ the alignment to byte/word/dword/qword 
>> alignment. This could be done with compiler `#pragma pack` or 
>> from C++/11 `alignas` or c/11 `_Alignas` (see 
>> https://en.cppreference.com/w/cpp/language/alignas)
>> to make sure the padding is the same.
>> - **do not** use bitfields since the packing of adjacent 
>> fields is implementation (compiler) dependent. (most probably 
>> the cause for diff in size 16 <==> 24 as you observed) see 
>> https://en.cppreference.com/w/cpp/language/bit_field
>> - make sure the type's used in the struct are architecture 
>> independent, size of int in c/c++ is dependent on target arch 
>> x86=> 32bits x86_64 64bits. Its fixed in D.
>> - make sure the size_t is the same type and size for all 
>> platforms
>> - use static struct in D
>> - use the correct corresponding types 
>> https://dlang.org/spec/type.html in D or use core.stdc.stdint 
>> type aliases
>
> I can not change c struct since I don't own the project but 
> need deal with it.

Do you know how this 'c' part is build? Which compiler and 
compiler flags?
Than you should be able to 'deduce' the alignment used an 
possibly the packing of bitfields.

When you know these things you are able to craft the D equivalent.

Another option is just to figure out the layout at runtime using 
a on purpose filled struct from 'c' with 'marker patterns' in the 
struct fields.



More information about the Digitalmars-d mailing list