www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Cast ptr/len to D-style array

reply James Blachly <james.blachly gmail.com> writes:
I work a lot with C functions, many of which yield pointer + length.

Is there a way to cast this or materialize a D-style array backed by the 
already allocated data (with length) to avoid copies which slow things down?

I recognize memory management is a complication. Typically, I would be 
responsible for free'ing the array later.

Thanks in advance
May 02 2019
parent reply ag0aep6g <anonymous example.com> writes:
On 02.05.19 22:03, James Blachly wrote:
 I work a lot with C functions, many of which yield pointer + length.
 
 Is there a way to cast this or materialize a D-style array backed by the 
 already allocated data (with length) to avoid copies which slow things 
 down?
Just slice the pointer with the length: int* ptr; size_t len; int[] arr = ptr[0 .. len];
May 02 2019
parent reply James Blachly <james.blachly gmail.com> writes:
On 5/2/19 4:05 PM, ag0aep6g wrote:
 Just slice the pointer with the length:
 
      int* ptr;
      size_t len;
      int[] arr = ptr[0 .. len];
Perfect thanks. I searched but without using the magic word "slice" I couldn't find meaningful results. Thanks again.
May 02 2019
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 05/02/2019 08:21 PM, James Blachly wrote:
 On 5/2/19 4:05 PM, ag0aep6g wrote:
 Just slice the pointer with the length:

 =C2=A0=C2=A0=C2=A0=C2=A0 int* ptr;
 =C2=A0=C2=A0=C2=A0=C2=A0 size_t len;
 =C2=A0=C2=A0=C2=A0=C2=A0 int[] arr =3D ptr[0 .. len];
=20 Perfect thanks. I searched but without using the magic word "slice" I=20 couldn't find meaningful results. =20 Thanks again.
Looks like I indexed it under "slice from pointer": http://ddili.org/ders/d.en/pointers.html#ix_pointers.slice%20from%20point= er Ali
May 03 2019
parent James Blachly <james.blachly gmail.com> writes:
On 5/3/19 5:42 AM, Ali Çehreli wrote:
 On 05/02/2019 08:21 PM, James Blachly wrote:
 On 5/2/19 4:05 PM, ag0aep6g wrote:
 Just slice the pointer with the length:

      int* ptr;
      size_t len;
      int[] arr = ptr[0 .. len];
Perfect thanks. I searched but without using the magic word "slice" I couldn't find meaningful results. Thanks again.
Looks like I indexed it under "slice from pointer": http://ddili.org/ders/d.en/pointers.html#ix_pointers.slice%20from%20pointer Ali
Thanks Ali, also helpful examples!
May 04 2019