Is there an easy way to convert a pointer to malloc'd memory to an array?
ZombineDev via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 25 01:52:34 PDT 2016
On Tuesday, 24 May 2016 at 18:42:41 UTC, Gary Willoughby wrote:
> I have a T* pointer to the start of a malloc'd chunk of memory,
> the type T and the number of T's stored in the chunk.
>
> Is there an efficient way of converting this information to a D
> array of type T[] or even T[n]?
BTW, the simplest way to use C malloc to allocate and initialize
a D array is with
http://dlang.org/phobos/std_experimental_allocator#makeArray:
struct MyObj { /* ... */ }
{
MyObj[] arr = Mallocator.instance
.makeArray!MyObj(10, ctorArgs);
scope (exit) Mallocator.instance.dispose(arr);
// use arr...
} // arr is freed at the end of the scope
Which is rougly equivalent to:
void* p = malloc(10 * MyObj.sizeof);
T[] arr = (cast(T*)p)[0 .. 10];
foreach (ref elem; arr)
emplace(elem, ctorArgs);
The benfit of using make* and dispose is that they allow you to
change the allocator if you so need. You can also use the GC:
int[] arr = GCAllocator.instance.makeArray!int(128);
// no need to free arr
The common idiom is that the user of a function that produces an
array should supply the allocator as a parameter through which
the function will make allocations. This useful when you know for
example that the allocation would be small and short-lived in
which case it would better to use a stack allocator, rather than
a heap allocator.
More information about the Digitalmars-d-learn
mailing list