From here (with minor edits under Python 3.5 and additional checks)
#include <Python.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pClass, *pInstance, *pValue; int i, arg[8]; if (argc < 4) { fprintf(stderr, "Usage: call module_name class_name method_name [arguments]\n"); return 1; } Py_Initialize(); // Преобразуем первый аргумент в unicode-строку python pName = PyUnicode_DecodeFSDefault(argv[1]); // Импортируем модуль // import module_name pModule = PyImport_Import(pName); Py_DECREF(pName); // Освобождаем ссылку на строку с именем модуля if (pModule != NULL) { // Получаем пространство имён (__dict__) модуля pDict = PyModule_GetDict(pModule); // Получаем класс class_name pClass = PyDict_GetItemString(pDict, argv[2]); // Проверяем, что полученный class_name можно вызвать if (pClass && PyCallable_Check(pClass)) { // Получаем объект // obj = class_name() pInstance = PyObject_CallObject(pClass, NULL); if(pInstance != NULL) { // Подготавливаем параметры if(argc > 4) { for (i = 0; i < argc - 4; i++) { arg[i] = atoi(argv[i + 4]); } // Вызываем метод с двумя параметрами // value = obj.multiply2(3, 2) pValue = PyObject_CallMethod(pInstance, argv[3], "(ii)", arg[0], arg[1]); } else { // Вызываем метод без параметров // value = obj.multiply() pValue = PyObject_CallMethod(pInstance, argv[3], NULL); } if (pValue != NULL) { printf("Return of call : %d\n", PyLong_AsLong(pValue)); // Освобождаем ссылку на выделенную в памяти // переменную для возвращённого из метода результата Py_DECREF(pValue); } else { PyErr_Print(); } Py_DECREF(pInstance); // Освобождаем ссылку на объект } else { PyErr_Print(); } Py_DECREF(pClass); // Освобождаем ссылку на класс } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find class \"%s\"\n", argv[2]); } Py_DECREF(pDict); // Освобождаем ссылку на пространство имён Py_DECREF(pModule); // Освобождаем ссылку на модуль } else { PyErr_Print(); } Py_Finalize(); return 0; }
As @jfs noted, this is just an example, the code is greatly simplified for clarity. In a combat project, the same operations will be twice as large as the code. Or four, if you need multithreading.
std::stringinto which to transfer all the commands necessary for execution inpythonand then just execute it usingPyRun_SimpleString( command for execution), but I would not like to use this solution. Ideally, I would like this scheme:std::vector<int> a = {1,2,3}declared in aC++file, then create an object of a class that is declared in thepythonmodule and that performs a lot of complex manipulations with this vector, execute them and return the result all in the sameC++module. - Zakharov AlekseypythoninC++. I want withinC++code to create an object of a class that is declared in thepythonmodule, to execute some methods of this class with this object declared in the samepythonmodule and get the result. (All this is insideC++code) - Zakharov Alekseyimport module; module.Klass(1).method("a", 2)import module; module.Klass(1).method("a", 2). It is usually better to extend Python than to build in (unless you create scripting capabilities for others like in Blender, Maya, Open Office). - jfs