boost.python:从嵌入式interp调用c++实例的成员函数

2024-04-29 11:40:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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的实例:

^{pr2}$

我想使用嵌入式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();
}

Tags: 实例表达式defmathvalresultfloatint