释放 PyTuple 对象
使用 Python C-API 释放 PyTuple 对象的正确方法是什么?
我知道元组在引用计数语义方面有些特殊,因为 PyTuple_SetItem
“窃取”对插入元素的引用。我还知道减少元组对象的引用会减少元组中所有元素的引用计数。
考虑到这一点,我认为应该可以肯定地说:
#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);
}
但是当我减少元组引用计数时,最后一行会导致分段错误。我不明白为什么会发生这种情况。在调用 Py_DECREF
之前,引用计数为 1
,那么这里有什么问题呢?
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_DECREF
the reference count is 1
, so what's the issue here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 main 的开头添加对
Py_Initialize();
的调用,然后重试。Add call to
Py_Initialize();
at the beginning of main and try again.