2016-10-02 4 views
1

次のPythonの埋め込みに関するドキュメントでは、Pythonのメソッドを "C"コードに埋め込む方法について詳しく説明しています。 https://docs.python.org/2/extending/embedding.htmlC++でのPythonオブジェクトの作成とそのメソッドの呼び出し

私は上記のコードをテストしました。これはg ++コンパイラでもうまく機能します。

しかし、上記の例では、クラスメソッドではなくグローバルメソッドを呼び出す例を示しています。

誰でもPythonオブジェクトを作成し、そのメソッドをC++から呼び出す方法についての例を表示できますか?

答えて

2

いくつかの調査を行うことで、これは次の4つのAPIを連続して使用することで可能であることがわかりました。

  • PyModule_GetDict; Pythonモジュールに属するアイテムを取得します。 *

  • PyDict_GetItemString; Pythonクラス の名前に対応する項目を取得します。

  • PyObject_CallObject; Pythonオブジェクトを作成します。 *
  • PyObject_CallMethod;オブジェクトのメソッドをクラス化します。

以下は、改善が必要な場合でも作成したサンプルコードです。

// Refer to the following website for more information about embedding the 
// Python code in C++. 
// https://docs.python.org/2/extending/embedding.html 
int main() { 
    PyObject *module_name, *module, *dict, *python_class, *object; 

    // Initializes the Python interpreter 
    Py_Initialize(); 

    module_name = PyString_FromString(
     "work.embedding_python_in_cpp.example.adder"); 

    // Load the module object 
    module = PyImport_Import(module_name); 
    if (module == nullptr) { 
    PyErr_Print(); 
    std::cerr << "Fails to import the module.\n"; 
    return 1; 
    } 
    Py_DECREF(module_name); 

    // dict is a borrowed reference. 
    dict = PyModule_GetDict(module); 
    if (dict == nullptr) { 
    PyErr_Print(); 
    std::cerr << "Fails to get the dictionary.\n"; 
    return 1; 
    } 
    Py_DECREF(module); 

    // Builds the name of a callable class 
    python_class = PyDict_GetItemString(dict, "Adder"); 
    if (python_class == nullptr) { 
    PyErr_Print(); 
    std::cerr << "Fails to get the Python class.\n"; 
    return 1; 
    } 
    Py_DECREF(dict); 

    // Creates an instance of the class 
    if (PyCallable_Check(python_class)) { 
    object = PyObject_CallObject(python_class, nullptr); 
    Py_DECREF(python_class); 
    } else { 
    std::cout << "Cannot instantiate the Python class" << std::endl; 
    Py_DECREF(python_class); 
    return 1; 
    } 

    int sum = 0; 
    int x; 

    for (size_t i = 0; i < 5; i++) { 
    x = rand() % 100; 
    sum += x; 
    PyObject *value = PyObject_CallMethod(object, "add", "(i)", x); 
    if (value) 
     Py_DECREF(value); 
    else 
     PyErr_Print(); 
    } 
    PyObject_CallMethod(object, "printSum", nullptr); 
    std::cout << "the sum via C++ is " << sum << std::endl; 

    std::getchar(); 
    Py_Finalize(); 

    return (0); 
} 
関連する問題