new int[]

Ali Çehreli acehreli at yahoo.com
Wed Jan 10 22:50:50 UTC 2018


On 01/10/2018 02:46 PM, ag0aep6g wrote:
> On 01/10/2018 11:35 PM, Luís Marques wrote:
>> Due to compatibility with some C code, I basically need to do this:
>>
>>      struct Wrapper
>>      {
>>          int[] x;
>>      }
>>
>>      void main()
>>      {
>>          void* ctxptr = new Wrapper([1, 2, 3]);
>>          auto context = cast(Wrapper*) ctxptr;
>>          writeln(context.x);
>>      }
>>
>> How can I do that without the wrapper? `new int[]` isn't supported, 
>> even though that's exactly what I want.
> 
> If I understand correctly, the goal is to have the `int[]` itself on the 
> GC heap. You can make an `int[][]` with one element, and then take the 
> address of that element:
> 
> ----
> void main()
> {
>      int[]* x = &[[1, 2, 3]][0];
>      int[]* x2 = [[1, 2, 3]].ptr; /* same */
> }
> ----

I was writing the same for a no-initial-value version:

void main() {
     void *v = cast(void*)((new int[][](1)).ptr);
     *(cast(int[]*)v) ~= 42;
}

I hope it's correct. :o)

Ali


More information about the Digitalmars-d-learn mailing list