C to D: please help translate this weird macro
Dejan Lekic
dejan.lekic at gmail.com
Wed Sep 20 17:14:41 UTC 2023
On Wednesday, 20 September 2023 at 13:55:14 UTC, Ki Rill wrote:
> On Wednesday, 20 September 2023 at 13:53:08 UTC, Ki Rill wrote:
>> Here is the macro:
>>
>> ```C
>> #define NK_CONTAINER_OF(ptr,type,member)\
>> (type*)((void*)((char*)(1 ? (ptr): &((type*)0)->member) -
>> NK_OFFSETOF(type, member)))
>> ```
>>
>> I'm trying to translate the Nuklear GUI library to D
>> [here](https://github.com/rillki/nuklear-d/tree/nuklear-d-translation).
>
> Here is how `NK_OFFSETOF` is defined:
> ```c
> #define NK_OFFSETOF(st,m) ((nk_ptr)&(((st*)0)->m))
> ```
NK_OFFSETOF is the same as D's struct `.offsetof` attribute.
NK_CONTAINER_OF should probably be translated to:
`cast(T*)((cast(void*)ptr - __traits(getMember, T,
member).offsetof))`
PS. I did not invent this. My original idea was far worse than
this. - It was suggested on IRC by a much cleverer D programmer
than myself - Herringway at IRC
More information about the Digitalmars-d-learn
mailing list