正在检查PyObject是否为null

2024-09-28 15:02:26 发布

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

我使用pythoncapi来填充包含PyObject*元素的列表,并将其传输到Python中的函数。一切都很顺利,但是有一个问题-Python中的transferredlist包含奇数<NULL>个条目。这个列表也包含了“想要的”对象,所以看起来它几乎可以工作了。在

以下是列表预览:

[<NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <NULL>, <dbg.TBack object at 0x19675870>, <interface.Grid object at 0x196758B0>, <interface.Grid object at 0x196758F0>, <interface.slp object at 0x196757D0>]

我在pythoncapi中用于填充列表的代码。在

^{pr2}$

我尝试过添加if(!handle)检查,但在实践中似乎没有任何效果。在

问题:如何删除列表中的<NULL>项?


Tags: 对象函数元素列表object条目nullinterface
2条回答

尝试this solution

if (handle == Py_None) {
    continue;
}   

或者

int PyObject_Not(PyObject *o)

Returns 0 if the object o is considered to be true, and 1 otherwise. This is equivalent to the Python expression not o. On failure, return -1.

否则,您可以检查handle的字符串表示形式。根据the documentation,您可以使用

^{pr2}$

我在想

^{3}$

问题在于如何分配列表。从the documentation到{}:

Note: If len is greater than zero, the returned list object’s items are set to NULL. Thus you cannot use abstract API functions such as PySequence_SetItem() or expose the object to Python code before setting all items to a real object with PyList_SetItem().

也就是说,它生成一个“len”空指针的列表,而不是生成一个带有预先分配空间的空列表。在

解决方案是:

  1. 创建一个空列表(passlen0),并保持其余代码不变(使用PyList_Append),或者
  2. 分配一个大小的列表,并使用PyList_SetItem而不是append。如果您使用这种方法,请注意PyList_setItem窃取了一个引用(因此您必须increfhandle),并且您想要的列表长度只包括那些带有getHandle()!=NULL的对象。在

相关问题 更多 >