translate C struct char array into D

jfondren julian.fondren at gmail.com
Fri Jul 30 17:04:00 UTC 2021


On Friday, 30 July 2021 at 14:05:58 UTC, workman wrote:
> I get want to define this struct in D:
>
> ```c
> struct test1 {
>     struct test1 *prev;
>     struct test1 *next;
>     size_t v1;
>     size_t v2;
>     size_t v3;
>     char data[];
> };
> ```

The easy way: put a slice there instead of a fake array and 
accept that data's contents will be allocated separately. Slices 
will be more convenient to deal with in the language anyway.

The C89 way: add a zero-length array and deal with its .ptr in 
appropriately sized allocations that you manage yourself (or get 
from a C API).

A third way: something with 
https://dlang.org/phobos/core_lifetime.html#.emplace

```d
import core.memory : pureMalloc, pureFree;
import std.conv : to;

struct Pascal {
     ubyte len;
     char[0] data;

     static Pascal* alloc(string s) {
         const len = s.length.to!ubyte;
         auto res = cast(Pascal*) pureMalloc(Pascal.sizeof + len);
         res.len = len;
         res.data.ptr[0 .. len] = s[0 .. len];
         return res;
     }

     char[] toString()() {
         return data.ptr[0 .. len];
     }
}

unittest {
     auto s = Pascal.alloc("hello");
     scope (exit) pureFree(s);
     assert(s.toString == "hello");
     assert((*s).sizeof == ubyte.sizeof);
}
```


More information about the Digitalmars-d-learn mailing list