在我的程序中,我在 C++ 中管理对 python 对象的引用。即我所有的类都是从引用类派生的,它包含指向相应python对象的指针。
class Referenced
{
public:
unsigned use_count() const
{
return selfptr->ob_refcnt;
}
void add_ref() const
{
Py_INCREF(selfptr);
}
void remove_ref() const
{
Py_DECREF(selfptr);
}
PyObject* selfptr;
};
我使用 intrusive_ptr 来保存从 Referenced 派生的对象。这使我可以轻松地在 C++ 中保留对所需 python 对象的引用,并在必要时访问它们。但是当要从 C++ 中删除 python 对象时,即当我调用 Py_DECREF(selfptr) 时,我的程序崩溃(仅在 windows howewer 中),selfptr->ob_refcnt == 1。这种方法可以吗?
Upd:我终于在我的程序中发现了问题。它与对象移除没有直接关系。为了检查最初的问题,我实现了简单的扩展模块,记住对 python 对象的引用并按需释放它。就这个:
#include <Python.h>
static PyObject* myObj;
static PyObject* acquirePythonObject(PyObject* self, PyObject* obj)
{
printf("trying to acquire python object %p, refcount = %d\n", obj, obj->ob_refcnt);
myObj = obj;
Py_INCREF(myObj);
printf("reference acquired\n");
return Py_True;
}
static PyObject* freePythonObject(PyObject*, PyObject*)
{
printf("trying to free python object %p, refcount = %d\n", myObj, myObj->ob_refcnt);
Py_DECREF(myObj);
printf("reference removed\n");
return Py_True;
}
static PyMethodDef moduleMethods[] =
{
{"acquirePythonObject", acquirePythonObject, METH_O, "hold reference to python object."},
{"freePythonObject", freePythonObject, METH_NOARGS, "free reference to python object."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initmodule(void)
{
Py_InitModule("module", moduleMethods);
}
和python脚本:
import module
class Foo:
def __init__(self):
print "Foo is created"
def __deinit__(self):
print "Foo is destroyed"
def acquireFoo():
foo = Foo()
module.acquirePythonObject(foo)
def freeFoo():
module.freePythonObject()
if __name__ == "__main__":
acquireFoo()
freeFoo()
示例在 windows 和 linux 中无缝运行。下面是输出。
Foo is created
trying to acquire python object 0x7fa19fbefd40, refcount = 2
reference acquired
trying to free python object 0x7fa19fbefd40, refcount = 1
Foo is destoryed
reference removed