我正在尝试使用boost.python
向我的应用程序添加Python脚本功能。我想要做的是使用Python来评估在我的C ++应用程序中分配的特定C ++类实例上的简单表达式。
我为C ++中的一个简单类编写了一个Python包装器:
class pyTest1
{
public:
pyTest1():i(1),f(3.14){}
int getint() { return i; }
void setint(int val) { i = val; }
float getfloat() { return f; }
void setfloat(float val) { f = val; }
private:
int i;
float f;
};
BOOST_PYTHON_MODULE(pyTestSpace)
{
class_<pyTest1>("pyTest1", init<>())
.def("getint", &pyTest1::getint)
.def("setint", &pyTest1::setint)
.def("getfloat", &pyTest1::getfloat)
.def("setfloat", &pyTest1::setfloat)
;
}
给出pyTest1
的实例:
pyTest1 *testInstance = new pyTest1;
我想使用嵌入式Python评估这样的表达式:
result = math.cos(testInstance->getfloat())
假设类实例和表达式(作为字符串)传递给C ++函数,如下所示:
#include <string>
#include <boost/python.hpp>
#include <graminit.h>
void UseEmbedPython(std::string exp, pyTest1* obj)
{
Py_Initialize();
initpyTestSpace();
PyObject *pDictionary = PyDict_New();
PyDict_SetItemString(pDictionary, "__builtins__", PyEval_GetBuiltins() );
PyRun_String("import math", file_input, pDictionary, pDictionary );
//Need help here!
//Assuming exp is something like "result = math.cos(obj->getfloat())"
//How do I make obj's functions accessible to Python interpretter?
PyRun_String(exp.c_str(), file_input, pDictionary, pDictionary );
PyObject *pResult = PyDict_GetItemString(pDictionary, "result" );
double result;
PyArg_Parse(pResult, "d", &result );
Py_Finalize();
}