From: marco g. <mar...@gm...> - 2011-02-01 14:55:01
|
Hello, i have to "swig" a c library with several structures that have some fields are pointers to some other malloc-ed memory. for example, struct foo { char *boo; } in c they are allocated ad deallocated with pair of functions struct foo* CreateFoo() { struct foo *ret = malloc(sizeof (*ret)); ret ->boo = malloc(100); return ret; } void DeleteFoo(struct foo* f) { free(f->boo); free(f); } I am targeting cshap; to avoid having memory leaks and invalid structures, and aving to call manually DeleteFoo(), I am doing this: // this is to avoid invalid foo allocated by new foo() %nodefaultctor foo; // this is to get the swigclass to own the memory %newobject CreateFoo; //this is to call lib.DeleteFoo when the object is destroyed %typemap(csdestruct, methodname="Dispose") foo { lock (this) { if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) { swigCMemOwn = false; lib.DeleteFoo(this); } swigCPtr = new HandleRef(null, IntPtr.Zero); GC.SuppressFinalize(this); } } Is this correct? Any better way to do ? Can I factor the typemap(csdestruct ...) instead of compypaste for every class in the library? Thank You in advance.. Ciao, Marco. -- "Reality continues to ruin my life." - Calvin. |