C to D: please help translate this weird macro

Nick Treleaven nick at geany.org
Thu Sep 21 16:28:25 UTC 2023


On Thursday, 21 September 2023 at 02:57:07 UTC, Ki Rill wrote:
> On Thursday, 21 September 2023 at 02:23:32 UTC, Ki Rill wrote:
>> wrote:
>>> [...]
>
> Translated it to this eventually:
> ```D
> auto nk_container_of(P, T)(P ptr, T type, const(char)* member)
> {
>     return cast(T*)(cast(void*)(cast(char*)
>         (ptr - __traits(getMember, type, member).offsetof)));
> }
> ```

The 1st argument of `getMember` can just be T, like the original 
macro.
The 2nd argument needs to be a compile-time string.
Also the `char*` cast needs to apply to `ptr` before subtracting 
the offset AFAICS.

So reordering to keep type inference of `ptr`:
```d
auto nk_container_of(T, string member, P)(P ptr)
{
     return cast(T*)(cast(void*)(cast(char*)ptr -
         __traits(getMember, T, member).offsetof)));
}
```
(Untested)


More information about the Digitalmars-d-learn mailing list