how to pass a ubyte[] to c interface?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 12 23:56:33 PDT 2015


On 03/12/2015 11:35 PM, zhmt wrote:

 > ubyte[] arr ;
 >
 > I pass the arr.ptr to c program

Unless there is sentinel value at the end of the array, you must also 
pass the number of elements (as Rikki Cattermole has shown).

However, if the C function holds on to that pointer for later use, you 
must also keep the array alive. You can ensure that by two general ways:

a) The D-side slice must not be a local slice. For example, it can be a 
member of a long-living object or it is a module-scope variable.

b) Tell the garbage collector that there is indeed a reference to that 
memory block somewhere else (even though there is no D-side reference to 
it). You can do this with GC.addRoot. (The opposite function is 
GC.removeRoot.)

 >, it fails silently.

That's not good.

 > Is there any way to cast a ubyte[] to a clang pointer?

Going off-topic, I think you mean the C language when you say "clang", 
which may be confusing because there is also the compiler called clang. :)

Ali



More information about the Digitalmars-d-learn mailing list