Access to structures defined in C

Atila Neves atila.neves at gmail.com
Wed Sep 19 10:56:55 UTC 2018


On Wednesday, 19 September 2018 at 00:46:54 UTC, Joe wrote:
> On Tuesday, 18 September 2018 at 13:47:50 UTC, Atila Neves 
> wrote:
> Sorry, Atila, I got confused looking at my two cases. I should 
> have said "an array of ints", e.g.,
>
> int yp[] = {2, 4, 0};
> int yq[] = {10, 12, 0};

That makes more sense.

>>> int *ys[] = {yp, yq, 0};
>>
>> This isn't even valid C code.
>
> It is, because C treats 'yp' as a pointer.

It wasn't with the definition of `yp` and `yq` you posted.

>
>>> In D, I first declared these as
>>>
>>> int[] yp = [2, 4];
>>> int[] yq = [10, 12];
>>> __gshared int*[] ys = [ &yp, &yq ];
>>
>> D dynamic arrays are not equivalent to C arrays.
>>
>> It's hard to see what you're trying to do with the code you 
>> posted. Have you tried instead to use a tool to translate the 
>> C headers?
>
> At this point, I've translated everything, even the code above. 
> I had to use 'immutable(int [])' in the second and higher level 
> arrays like 'ys' so that they could refer to 'yp' and 'yq' 
> (without the address operators).

This would be the literal translation:

int[3] yp = [2, 4, 0];
int[3] yq = [10, 12, 0];
int*[3] ys;

shared static this() {
     ys = [yp.ptr, yq.ptr, null];
}


> However, I still would like to have a deeper understanding of 
> the "static variable yp cannot be read at compile time" error 
> messages which went away when I declared yp immutable.

I guess immutable makes everything known at compile-time? I 
didn't even know that was a thing. In any case, the reason why 
you got those error messages is because initialisation of global 
variables in D happens at compile-time. If you want runtime 
initialisation like in C++, you have to use static constructors 
like in my code above.




More information about the Digitalmars-d-learn mailing list