开发者

Freeing a PyTuple object

What is the proper way to free a PyTuple object using the Python C-API?

I know that tuples are somewhat special when it comes to the reference counting semantics, since PyTuple_SetItem "steals" the reference to the inserted element. I also know that decrementing the reference of a tuple object decrements the reference count of all the elements in the tuple.

With this in mind, I would think it should be safe to say:

#include <Python.h>
#include <stdio.h>

int main()
{
    PyObject* tup = PyTuple_New(1);
    PyTuple_SetItem(tup, 0, PyLong_FromLong(100L));

    printf("Ref Count: %d\n", tup->ob_refcnt);
    Py_DECREF(tup);
}

But the last line causes a Segmentation Fault, when I decrement the tuple reference count. I don't understand why this happens. Right before the call to Py_DECRE开发者_如何学PythonF the reference count is 1, so what's the issue here?


Add call to Py_Initialize(); at the beginning of main and try again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜