PyObject\u CallObject在bytearray方法上失败

2024-09-30 06:14:29 发布

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

在下面的代码中,我使用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),并验证了该对象是可调用的。我的错误是什么?在


Tags: the代码pytrueifincludebytenull
1条回答
网友
1楼 · 发布于 2024-09-30 06:14:29

如果您添加^{}行,它将有用地告诉您:

TypeError: argument list must be a tuple

这由the documentation for ^{}确认:

Call a callable Python object callable_object, with arguments given by the tuple args.

从C-api调用函数有很多种方法。我选了一个不需要元组的,它对我很管用(但是选一个你喜欢的):

PyObject* shouldbetrue = PyObject_CallFunctionObjArgs(arrayEndsWith, oneByteArray,NULL);

相关问题 更多 >

    热门问题