static init c struct with array filed

Ali Çehreli acehreli at yahoo.com
Wed Mar 16 18:04:29 UTC 2022


On 3/16/22 10:03, user1234 wrote:
 > On Wednesday, 16 March 2022 at 14:42:02 UTC, Era Scarecrow wrote:
 >> On Wednesday, 16 March 2022 at 11:27:20 UTC, user1234 wrote:
 >>> assuming the c library takes by reference
 >>
 >>  My experience all arrays are effectively just pointers
 >
 > I meant the function that takes the Test2 as parameter, but to be honest
 > I dont get exactly what does OP want actually...

They want to pass Test2 to C and be able to use it. D ABI defines arrays 
(slices) as a pair of size_t and a pointer:

   https://dlang.org/spec/abi.html#arrays

I haven't passed such a struct to C but I believe the equivalent C 
struct can assume there are the following members in place of the array:

struct Test2 {
     int32_t a;
     size_t length;
     Test * ptr;
}

However, the lifetime of ptr must be ensured on the D side because 
utless there is a reference to it on the D side, the GC can free the 
memory at any time and C side may access invalid memory.

That is explained here:

   https://dlang.org/spec/interfaceToC.html#storage_allocation

Ali



More information about the Digitalmars-d-learn mailing list