1

我正在尝试使用boost.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();
}
4

0 回答 0