【问题标题】:Creating a python object in C++ and calling its method在 C++ 中创建一个 python 对象并调用它的方法
【发布时间】:2016-10-02 02:29:32
【问题描述】:

在下面关于python嵌入的文档中,很好地描述了如何在“C”代码中嵌入python方法。 https://docs.python.org/3/extending/embedding.html

我测试了上面的代码,它在 GCC g++ 编译器上也能很好地工作。

但上面显示了调用全局方法而不是类方法的示例。

谁能展示一个关于如何创建 Python 对象并从 C++ 调用其方法的示例?

【问题讨论】:

    标签: python c++


    【解决方案1】:

    通过调查,我发现这可以通过串联使用以下四个API来完成。

    • PyModule_GetDict ;获取属于 python 模块的项目。 *

    • PyDict_GetItemString ;获取Python类对应的item 姓名。

    • PyObject_CallObject;创建 Python 对象。 *
    • PyObject_Call 方法;类对象的方法。

    以下是我创建的示例代码,尽管它仍然需要改进。

    // 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);
    }
    

    【讨论】:

    • 非常感谢这段代码。如果您也包含 python 代码以提供更好的想法,那就太好了。
    猜你喜欢
    • 2012-12-28
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多