www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Allocating byte aligned array

reply timvol <timvol unknownmailaddress.com> writes:
Hi guys,
how can I allocate an (e.g. 16) byte aligned array?
In C I can do the following:

     void *mem = malloc(1024+15);
     void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
     memset_16aligned(ptr, 0, 1024);
     free(mem);

I think in D it looks similar to this:

     auto mem = new ubyte[1024+15];
     auto ptr = (mem.ptr + 15) & ~ (...???...) 0x0F;

How to fill ...???... ?
Without a cast, the compiler tells me that I the types are 
incompatible (ubyte* and int).

What's the correct syntax here?

PS: I don't want to use the experimental branch that provides 
alignedAllocate().
Sep 27
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 09/27/2017 02:39 PM, timvol wrote:
 Hi guys,
 how can I allocate an (e.g. 16) byte aligned array?
 In C I can do the following:

     void *mem = malloc(1024+15);
     void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
     memset_16aligned(ptr, 0, 1024);
     free(mem);

 I think in D it looks similar to this:

     auto mem = new ubyte[1024+15];
     auto ptr = (mem.ptr + 15) & ~ (...???...) 0x0F;

 How to fill ...???... ?
 Without a cast, the compiler tells me that I the types are incompatible
 (ubyte* and int).

 What's the correct syntax here?

 PS: I don't want to use the experimental branch that provides
 alignedAllocate().
void main() { auto mem = new ubyte[1024+15]; auto ptr = cast(ubyte*)(cast(ulong)(mem.ptr + 15) & ~0x0FUL); auto arr = ptr[0..1024]; } Ali
Sep 27
parent reply timvol <timvol unknownmailaddress.com> writes:
On Wednesday, 27 September 2017 at 21:44:48 UTC, Ali Çehreli 
wrote:
 On 09/27/2017 02:39 PM, timvol wrote:
 [...]
void main() { auto mem = new ubyte[1024+15]; auto ptr = cast(ubyte*)(cast(ulong)(mem.ptr + 15) & ~0x0FUL); auto arr = ptr[0..1024]; } Ali
Works perfect. Thank you!
Sep 27
parent Igor <stojkovic.igor gmail.com> writes:
On Wednesday, 27 September 2017 at 21:48:35 UTC, timvol wrote:
 On Wednesday, 27 September 2017 at 21:44:48 UTC, Ali Çehreli 
 wrote:
 On 09/27/2017 02:39 PM, timvol wrote:
 [...]
void main() { auto mem = new ubyte[1024+15]; auto ptr = cast(ubyte*)(cast(ulong)(mem.ptr + 15) & ~0x0FUL); auto arr = ptr[0..1024]; } Ali
Works perfect. Thank you!
I know you can also use this with static arrays: align(16) ubyte[1024] mem; But I guess align directive doesn't work with dynamic arrays...
Sep 29