简体   繁体   English

Python object 中的 C++ 对象包装器未销毁

[英]C++ objects wrapper in Python object not destroyed

I noticed that C++ objects wrapped in Python object were not destroyed when the Python object was released. 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:这是我使用 CPython C API 的类型定义:

typedef struct {
    PyObject_HEAD
    CppFoo fooObj;
    std::vector<Py_ssize_t> size;
} FooObject;

And this is the tp_dealloc:这是 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:在 Python 中调用以下代码时,调试器中会命中 FooObject_dealloc:

>>>myfoo=Foo()
>>>del myfoo

However, the destructor of CppFoo was not called even though the constructor was called in tp_init.但是,即使在 tp_init 中调用了构造函数,也没有调用 CppFoo 的析构函数。 How could this happen?这怎么可能发生? Shouldn't the destructor of CppFoo called automatically when myfoo is released?释放 myfoo 时不应该自动调用 CppFoo 的析构函数吗? What should be done to avoid the leak of fooObj?应该怎么做才能避免fooObj的泄漏?

EDIT: I pretty much followed the tutorial in the creation of the type:编辑:我在创建类型时几乎遵循了教程:

https://docs.python.org/3/extending/newtypes_tutorial.html 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.不同之处在于我在 PyObject_HEAD 之后将 C++ 对象添加到除 int 或 PyObject* 之外的类型。

In C++, construction of objects using dynamic memory involves two steps:在 C++ 中,使用动态 memory 构造对象涉及两个步骤:

  1. Allocate memory for the object(s).为对象分配 memory。
  2. Initialize the object(s) using a valid constructor.使用有效的构造函数初始化对象。

On the other side, destruction of objects using dynamic memory also involves two steps:另一方面,使用动态 memory 销毁对象也涉及两个步骤:

  1. Call the destructor to destruct the object(s).调用析构函数来销毁对象。
  2. Deallocate the memory for the object(s).为对象释放 memory。

It's unclear from your post how you are constructing the object but the problem with the destruction is clear.从您的帖子中不清楚您是如何构建 object 的,但破坏的问题很明显。 You have code for step 2 but not for step 1.您有第 2 步的代码,但没有第 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.在我看到您构建 object 的代码之前,我不想建议一种具体的方法来正确处理 object 的破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM