在Python C扩展上,CudioDeLoC上的C++类是否应该调用DELL或PYXXReDFF?

2024-06-30 07:49:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下配置:

#include "custom.hpp"

typedef struct
{
    PyObject_HEAD
    FastFile* cppobjectpointer;
}
PyFastFile;

static int PyFastFile_init(PyFastFile *self, PyObject *args, PyObject *kwds) {
    self->cppobjectpointer = new FastFile( filepath );
    return 0;
}

如何释放我的cppobjectpointer?你知道吗

我应该这样做:

static void PyFastFile_dealloc(PyFastFile * self)
{
    delete self->cppobjectpointer;
    Py_TYPE(self)->tp_free( (PyObject *) self );
}

或者这个:

static void PyFastFile_dealloc(PyFastFile * self)
{
    Py_XDECREF(self->cppobjectpointer);
    Py_TYPE(self)->tp_free( (PyObject *) self );
}

参考文献:

  1. How to wrap a C++ object using pure Python Extension API (python3)?
  2. https://pythonextensionpatterns.readthedocs.io/en/latest/refcount.html
  3. When to Py_INCREF?
  4. https://docs.python.org/3/extending/extending.html#ownership-rules
  5. Where should I put Py_INCREF and Py_DECREF on this block in Python C Extension?

Tags: topyhttpsselffreetypeextensionstatic