简体   繁体   English

PyObject_CallObject在bytearray方法上失败

[英]PyObject_CallObject failing on bytearray method

In the following code I create a pointer to a PyObject, representing a bytearray, using the Python C API. 在下面的代码中,我使用Python C API创建一个指向PyObject的指针,表示一个bytearray。 I then extract the method "endswith" from the bytearray and try to call it on the original bytearray itself, expecting it to return Py_True. 然后我从bytearray中提取方法“endswith”并尝试在原始bytearray本身上调用它,期望它返回Py_True. However, it returns NULL and the program prints "very sad". 但是,它返回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;
}

I have checked in Python that for bytearrays, foo and bar , foo.endswith(bar) returns a Boolean. 我在Python中检查过,对于bytearrays, foobarfoo.endswith(bar)返回一个布尔值。 I also added PyCallable_Check(arrayEndsWith) to the code above and verified that the object is callable. 我还在上面的代码中添加了PyCallable_Check(arrayEndsWith)并验证了该对象是可调用的。 What is my mistake? 我的错是什么?

If you add the line PyErr_PrintEx(1) it helpfully tells you: 如果你添加PyErr_PrintEx(1)PyErr_PrintEx(1)告诉你:

TypeError: argument list must be a tuple TypeError:参数列表必须是元组

This is confirmed by the documentation for PyObject_CallObject : PyObject_CallObject的文档证实了这一点:

Call a callable Python object callable_object, with arguments given by the tuple args. 使用元组args给出的参数调用可调用的Python对象callable_object。

There's a whole bunch of ways of calling functions from the C-api. 从C-api调用函数有很多种方法。 I picked one that doesn't require a tuple and it works for me (but pick the one you like): 我挑选了一个不需要元组的东西,它适用于我(但选择你喜欢的那个):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM