[cffi-devel] New and delete pertaining C wrapper for C++ code

Daniel Herring dherring at tentpost.com
Sat Mar 22 21:31:32 UTC 2014


On Sat, 22 Mar 2014, Joeish W wrote:

> I have a whole list of C wrappers for OpenCV C++ functions like the one below. And all of them return a "new".  I can't change them because they are becoming part of OpenCV and it would make my library perfect to have a consistently
> updated skeleton to wrap around. My question is in this case how would one of you free these "new" memory allocators...When I run them in any kind of loop.  It just eats up my ram, I end up having to restart my pc. Should I make a
> "delete" wrapper and use that.
> I've tried using foreign-free but I still have the same issue of having to restart. Any help is appreciated.
> 
> Mat* cv_create_Mat() {
>     return new Mat();
> }


Hi Joeish,

Long story short, you need to follow new() with delete().

C++ new() and delete() extend C's malloc() and free() in roughly the 
following way.

T * new(args) {
   T *x=(T *)malloc(sizeof(T));
   x->T(args); // constructor (aka ctor)
   return x;
}

void delete(T *x) {
   if(x) {
     x->~T(); // destructor (aka dtor)
     free(x);
   }
}

Note that both the constructor and destructor are fairly arbitrary 
functions, and it is common for them to do additional memory management.


- Daniel


More information about the cffi-devel mailing list