how to handle memory ownership when interfacing with C/C++ via internal pointers

Timothee Cour thelastmammoth at gmail.com
Thu Oct 10 16:02:19 PDT 2013


Short version:
I have a struct A* aptr allocated in C/C++ with an internal
pointer aptr->ptr (say a double*)
I want to store a reference x (say double[]) in D to aptr only through
aptr->ptr, not through aptr directly as it's inconvenient in my use case.

How do I achieve that, so that when x goes out of scope, some deallocator
for aptr will be called ?

Long version:
----
suppose I have C++ code:
struct A{
  double*ptr;
  A(size_t n){ptr=(double*)malloc(n);}
  ~A(){free(ptr);}
};

and a D wrapper around it:
extern(C){struct A; A*A_new(size_t n); void A_delete(A*a);
double*A_ptr(A*a);}

I want to use it as follows:

double[] get_x(size_t n){
 return A_new(n).A_ptr[0..n];
}

void main(){
  double[]x=get_x(n);
// do something with x;
}
----

It's trivial to handle this via a class wrapper:
class A2{
A*a;
this(size_t n){a=A_new(n);}
~this(){A_delete(n);}
double*ptr(){return A_ptr(a);}
}
double[] get_x(size_t n){
 auto a2=new A2(n);
 return a2.ptr;
//this doesn't help much though, A2 will go out of scope when this function
exits.
}


but I don't want to maintain objects of class A2 around, just double[]
slices as above.

Is there some magic involving core.memory.addRoot,addRange (etc) I can use
so that a2 stays alive as long as x stays alive? (in which case when x goes
out of scope, 'a2' will too, and will call A_delete).

Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20131010/6de428f6/attachment-0001.html>


More information about the Digitalmars-d-learn mailing list