D as an extension language for C

Walter Bright newshound2 at digitalmars.com
Wed May 17 03:52:33 UTC 2023


On 5/16/2023 6:36 AM, Adam D Ruppe wrote:
> ImportC can do C bitfields, but since they're layout is undefined it is useless 
> anyway.

Pedantically, the C layout is not undefined, it is implementation defined. D's 
bitfields, however, are defined to match the layout of the associated C compiler.

But as a practical matter, if you stick with `int` and `unsigned` bit field 
types, the layout is consistent across compilers with 32 bit ints. Any other 
differences would only be a problem if data is moved between systems. The C code 
will still work.

It's analogous to the size of `int` being implementation defined, along with the 
size of `char`, `long`, `long long`, the signedness of char being implementation 
defined, whether it's ones or twos complement, and so on. But C remained useful.

mportC also implements a number of half-specified associated C compiler 
extensions, because (sadly) nearly all of the C header files unnecessarily rely 
on these extensions.

Ironically, by making D bitfields match the associated C compiler's, it arguably 
makes D bitfields *more* portable.


> (Walter also copied importC's awful bitfields into D, but I hope that mistake is 
> reverted.)

There's always https://dlang.org/phobos/std_bitmanip.html#bitfields which do 
have a portable defined format.

Note that nobody has implemented in Phobos a bitfield setup that matches the 
associated C compiler's bit fields, making such C constructs difficult to access 
from D. They're easy now!


More information about the Digitalmars-d mailing list