Я пытаюсь встроить скрипт Python в свою программу на C++. После прочтения некоторых вещей о внедрении и расширении я понимаю, как открыть свой собственный скрипт python и как передать некоторые целые числа. Но теперь я в какой-то момент не понимаю, как решить мою проблему. Я должен сделать оба, вызывая функции Python из C++ и вызывая функции C++ из моего встроенного сценария Python. Но я не знаю, с чего начать. Я знаю, что мне нужно скомпилировать файл .so, чтобы разоблачить мои функции C++ для Python, но это ничего не могу сделать, потому что мне нужно встроить свой файл Python и управлять им с помощью кода на C++ (мне нужно расширить большое программное обеспечение с помощью язык скриптов, чтобы сделать некоторую логику легко отредактированной).Вложение Python в C++ и методы вызова из кода C++
Итак, есть ли способ сделать обе вещи? Вызов функций Python из C++ и вызов функций C++ из Python?
Это мой C++ кода
#include <Python.h>
#include <boost/python.hpp>
using namespace boost::python;
// <----------I want to use this struct in my python file---------
struct World
{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
// Exposing the function like its explained in the boost.python manual
// but this needs to be compiled to a .so to be read from the multiply.py
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}
// <---------------------------------------------------------------
int
main(int argc, char *argv[]) // in the main function is only code for embedding the python file, its not relevant to this question
{
setenv("PYTHONPATH",".",1);
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
int i;
if (argc < 3) {
fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
return 1;
}
Py_Initialize();
pName = PyString_FromString(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(argc - 3);
for (i = 0; i < argc - 3; ++i) {
pValue = PyInt_FromLong(atoi(argv[i + 3]));
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
/* pValue reference stolen here: */
PyTuple_SetItem(pArgs, i, pValue);
}
pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyInt_AsLong(pValue));
Py_DECREF(pValue);
}
else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr,"Call failed\n");
return 1;
}
}
else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
return 1;
}
Py_Finalize();
return 0;
}
и это мой файл Python
import hello_ext #importing the C++ file works only if its compiled as a .so
planet = hello.World() #this class should be exposed to python
planet.set('foo')
def multiply(a,b):
planet.greet()
print "Will compute", a, "times", b
c = 0
for i in range(0, a):
c = c + b
return c
Если это не ясно, я ищу что-то вроде 'lua_register (lua_State * L, имя строки, функция func)' для python. – Ventu