在下面的代码中,我使用pythoncapi创建了一个指向PyObject的指针,表示bytearray。然后,我从bytearray中提取方法“endswith”,并尝试在原始bytearray本身上调用它,期望它返回Py_True.
,但是它返回NULL
,程序输出“非常悲伤”。在
#include<Python.h>
#include<iostream>
int main()
{
Py_Initialize();
//make a one-byte byte array
PyObject* oneByteArray = PyByteArray_FromStringAndSize("a", 1);
//get the method "endswith" from the object at oneByteArray
PyObject* arrayEndsWith = PyObject_GetAttrString(oneByteArray, "endswith");
//ask python if "a" ends with "a"
PyObject* shouldbetrue = PyObject_CallObject(arrayEndsWith, oneByteArray);
if (shouldbetrue == Py_True) std::cout << "happy\n";
if(shouldbetrue == NULL)std::cout << "very sad\n";
Py_Finalize();
return 0;
}
我在Python中检查过,对于bytearray,foo
和{foo.endswith(bar)
返回一个布尔值。我还向上面的代码添加了PyCallable_Check(arrayEndsWith)
,并验证了该对象是可调用的。我的错误是什么?在
如果您添加^{} 行,它将有用地告诉您:
这由the documentation for ^{} 确认:
从C-api调用函数有很多种方法。我选了一个不需要元组的,它对我很管用(但是选一个你喜欢的):
相关问题 更多 >
编程相关推荐