Consider the following python ctypes – c++ binding:
// C++
class A
{
public:
void someFunc();
};
A* A_new() { return new A(); }
void A_someFunc(A* obj) { obj->someFunc(); }
void A_destruct(A* obj) { delete obj; }
# python
from ctypes import cdll
libA = cdll.LoadLibrary(some_path)
class A:
def __init__(self):
self.obj = libA.A_new()
def some_func(self):
libA.A_someFunc(self.obj)
What’s the best way to delete the c++ object, when the python object is not needed any more.
[edit]
I added the delete function that was suggested, however the problem remains by whom and when the function is called. It should be as convenient as possible.
You could implement the
__del__method, which calls a destructor function you would have to define:C++
Python
Also note that you left out the
selfparameter on the__init__method. Futhermore, you have to specify the return type/argument type explicitly, because ctypes defaults to 32 bit integers, while a pointer is likely 64 bits on modern systems.Some think
__del__is evil. As an alternative, you can usewithsyntax: