2016-10-06 6 views
3

次のコードでは、Python C APIを使用してbytearrayを表すPyObjectへのポインタを作成します。私はその後、bytearrayから "endswith"メソッドを抽出し、元のbytearray自体を呼び出して返すようにしようとしましたが、Py_True.を返します。しかし、それはNULLを返し、プログラムは "非常に悲しい"を返します。bytearrayメソッドでPyObject_CallObjectが失敗する

#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; 
} 

私がByteArrayとして定義するために、foobarは、foo.endswith(bar)ブールを返すことはPythonでチェックしています。また、上記のコードにを追加し、そのオブジェクトが呼び出し可能であることを確認しました。私の間違いは何ですか?

答えて

1

それは親切を示していますあなたが行を追加する場合:

TypeError: argument list must be a tuple

をこれはthe documentation for PyObject_CallObjectによって確認されています

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

C-APIから関数を呼び出す方法の全体の束があります。私はタプルを必要としないものを選び、それは私のために働きます(ただしあなたが好きなものを選んでください):

PyObject* shouldbetrue = PyObject_CallFunctionObjArgs(arrayEndsWith, oneByteArray,NULL); 
関連する問題