Reuse C memory for D struct?

Lemonfiend lemon at fie.nd
Mon Nov 25 09:37:58 PST 2013


On Thursday, 21 November 2013 at 19:21:10 UTC, Ali Çehreli wrote:
> On 11/21/2013 07:22 AM, Lemonfiend wrote:
>
> > I'm wondering if it's possible to have a struct in D which
> uses the same
> > pointer and memory as returned by the extern C function.
> > This would allow me to manipulate and use the C struct
> directly in D code.
> >
> > I'm not sure how to better explain this, hopefully the
> following
> > pseudocode clarifies my question
> >
> > struct Tree
> > {
> >      enum treeSize = 40;
> >
> >      ubyte[treeSize] _this;
> >
> >      this(int apples)
> >      {
> >          // use the C provided pointer somehow?
> >          // neither of the following seem to do the trick
> >          //this = *cppNew(apples);
> >          //_this = *cast(ubyte*)cppNew(apples)
>
> If you instead maintain a slice of Apples and assuming that 
> 'apples' is the number of apples, then you can use the 
> following syntax
>
>     Apple[] _this;
>
> // ...
>
>     _this = cppNew[0 .. apples];
>
> I have some information about that syntax under the "Producing 
> a slice from a pointer" section here:
>
>   http://ddili.org/ders/d.en/pointers.html
>
> One thing that is not mentioned in there is that you are still 
> responsible for the Apples that are returned by the C library.
>
> Ali

I had previously attempted this, but without success.
So I decided to give it another try your way.

Slicing is tricky!

ubyte[] _this;
vs
ubyte[size] _this;

and

_this = cPointer[0 .. size];
vs
_this[] = cPointer[0 .. size];


After trying all variations, it still didn't work.
Then a colleague noticed I was checking the results with:

&_this
vs
_this.ptr

I had thought those would give the same result, but apparently 
not?

So in the end it worked:
ubyte[] _this;
_this = cPointer[0 .. size];
_this.ptr == cPointer: true

Thanks! (and apologies for the late reply)


More information about the Digitalmars-d-learn mailing list