中创建python对象并调用其方法

中创建python对象并调用其方法

本文介绍了在C ++中创建python对象并调用其方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下有关python嵌入的文档中,很好地描述了如何将python方法嵌入到 C中。码。

In the following document about python embedding, it is well described how to embed python methods in "C" code.https://docs.python.org/3/extending/embedding.html

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

I tested the above code, it works well with the GCC g++ compiler as well.

但是上面显示了示例

有人可以显示一个有关如何创建Python对象并从C ++调用其方法的示例吗?

Could anyone show an example about how to create a Python object and call its method from C++?

推荐答案

通过做一些调查,我发现可以使用以下四个API来完成。

By doing some investigation, I found that this can be done using the following fourAPIs in series.


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

  • PyModule_GetDict ; Gets items belonging to the python module. *

PyDict_GetItemString;获取与Python类
名称相对应的项。

PyDict_GetItemString ; Gets the item corresponding to Python classname.

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

The following is the sample code that I created even though it still needs to be improved.

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

这篇关于在C ++中创建python对象并调用其方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 16:00