Converting void* to D array

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Apr 15 04:18:02 PDT 2015


On 4/15/15 12:47 AM, Daniel Kozak wrote:
> On Wednesday, 15 April 2015 at 04:43:39 UTC, Daniel Kozák wrote:
>>
>> On Wed, 15 Apr 2015 04:24:20 +0000
>> Craig Dillabaugh via Digitalmars-d-learn
>> <digitalmars-d-learn at puremagic.com> wrote:
>>
>>> Hi.
>>> I want to call a C library function that returns a data buffer as a
>>> void*.  How do I convert the resulting void* into something I can
>>> process in D?
>>>
>>> //I have the following function from the GDAL C library.
>>> extern(C) CPLErr GDALReadBlock( GDALRasterBandH, int, int, void* );
>>>
>>>
>>> So I have (GByte is defined in the GDAL library):
>>>
>>> void* buffer = malloc( GByte.sizeof * x_block_size * y_block_size );
>>>
>>> I fill the buffer (and ignore any errors :o)
>>>
>>> GDALReadBlock( AGDALRasterBandHInstance, xblock, yblock, buffer );
>>>
>>>
>>> Now, how can I access the data in buffer?
>> Or you probably can do it like this:
>>
>> auto buffer = new GByte[xblock*yblock];
>>
>> GDALReadBlock( AGDALRasterBandHInstance, xblock, yblock,
>> (cast void*)buffer.ptr );
> But in this case memory will be scan by GC. Which probably is not
> something what you want.

Depends on what GByte is. If it doesn't contain pointers (I'm assuming 
its probably ubyte?), then it won't be scanned.

If you still want to use malloc, but in a safe way, you can do:

immutable blocksize = GByte.sizeof * x_block_size * y_block_size;
auto buffer = malloc(blocksize)[0..blocksize];

Also, you don't need to cast pointers to void *. Should be able to do:

GDALReadBlock(AGDALRasterBandHInstance, xblock, yblock, buffer.ptr);

-Steve


More information about the Digitalmars-d-learn mailing list