I noticed that C++ objects wrapped in Python object were not destroyed when the Python object was released.
Here is my type definition using CPython C API:
typedef struct {
PyObject_HEAD
CppFoo fooObj;
std::vector<Py_ssize_t> size;
} FooObject;
And this is the tp_dealloc:
void FooObject_dealloc(FooObject* self) {
Py_TYPE(self)->tp_free((PyObject*)self);
}
The FooObject_dealloc is hit in the debugger when following code is called in Python:
>>>myfoo=Foo()
>>>del myfoo
However, the destructor of CppFoo was not called even though the constructor was called in tp_init. How could this happen? Shouldn't the destructor of CppFoo called automatically when myfoo is released? What should be done to avoid the leak of fooObj?
EDIT: I pretty much followed the tutorial in the creation of the type:
https://docs.python.org/3/extending/newtypes_tutorial.html
The difference is that I added C++ objects to the type other than int or PyObject* after PyObject_HEAD.
In C++, construction of objects using dynamic memory involves two steps:
On the other side, destruction of objects using dynamic memory also involves two steps:
It's unclear from your post how you are constructing the object but the problem with the destruction is clear. You have code for step 2 but not for step 1.
I don't want to suggest a concrete way to correctly deal with destruction of the object until I see your code for constructing the object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.