Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 摧毁一个物体_Python_C_Cpython - Fatal编程技术网

Python 摧毁一个物体

Python 摧毁一个物体,python,c,cpython,Python,C,Cpython,根据,PyCapsule_New()的第三个参数可以指定一个析构函数,我假设应该在胶囊被销毁时调用它 void mapDestroy(PyObject *capsule) { lash_map_simple_t *map; fprintf(stderr, "Entered destructor\n"); map = (lash_map_simple_t*)PyCapsule_GetPointer(capsule, "MAP_C_API"); if (map ==

根据,PyCapsule_New()的第三个参数可以指定一个析构函数,我假设应该在胶囊被销毁时调用它

void mapDestroy(PyObject *capsule) {

    lash_map_simple_t *map;
    fprintf(stderr, "Entered destructor\n");
    map = (lash_map_simple_t*)PyCapsule_GetPointer(capsule, "MAP_C_API");
    if (map == NULL)
         return;
    fprintf(stderr, "Destroying map %p\n", map);
    lashMapSimpleFree(map);
    free(map);

}

static PyObject * mapSimpleInit_func(PyObject *self, PyObject *args) {

    unsigned int w;
    unsigned int h;
    PyObject *pymap;

    lash_map_simple_t *map = (lash_map_simple_t*)malloc(sizeof(lash_map_simple_t));

    pymap = PyCapsule_New((void *)map, "MAP_C_API", mapDestroy);

    if (!PyArg_ParseTuple(args, "II", &w, &h))
        return NULL;

    lashMapSimpleInit(map, &w, &h);

    return Py_BuildValue("O", pymap);

} 
但是,当我实例化对象并将其删除或从Python控制台退出时,似乎不会调用析构函数:

>>> a = mapSimpleInit(10,20)
>>> a
<capsule object "MAP_C_API" at 0x7fcf4959f930>
>>> del(a)
>>> a = mapSimpleInit(10,20)
>>> a
<capsule object "MAP_C_API" at 0x7fcf495186f0>
>>> quit()
lash@CANTANDO ~/programming/src/liblashgame $ 
>a=mapSimpleInit(10,20)
>>>a
>>>德尔(a)
>>>a=mapSimpleInit(10,20)
>>>a
>>>退出
lash@CANTANDO~/programming/src/liblashgame$
我猜这与
Py_BuildValue()
返回对“capsule”的新引用有关,删除后不会影响原始引用。无论如何,我该如何确保该对象被正确销毁

使用Python3.4.3[GCC4.8.4](在linux上)

Py_BuildValue(“O”,thingy)
只会增加
thingy
的refcount并返回它–文档说它返回一个“新引用”,但当您传递一个现有的
PyObject*
时,这并不完全正确

如果您的这些函数——也就是您问题中的函数——都是在同一个翻译单元中定义的,则析构函数很可能必须声明为
static
(因此其完整签名将是
static void mapDestroy(PyObject*capsule);
)确保Python API在调用析构函数时能够正确查找函数的地址


…只要析构函数在内存中的地址有效,就不必使用
静态
函数。例如,我已经成功地使用了,因为非捕获C++ LAMBDAS可以转换为函数指针;如果您想使用另一种方法获取和传递胶囊析构函数的函数指针,并且该函数指针对您更有效,请务必使用它。

上面的代码有一个引用泄漏:
pymap=PyCapsule\u New()
返回一个新对象(其refcount为1),但
Py\u BuildValue(“O”,pymap)
创建对同一对象的新引用,其引用计数现在为2

只需
返回pymap