7

I want use embed python in c++ app and call functions defined in python script. The function's parameter is a c++ object. See my code:

class Test
{
public:
    void f()
    {
        std::cout<<"sss"<<std::endl;
    }
};

int main()
{
    Py_Initialize();
    boost::python::object main = boost::python::import("__main__");
    boost::python::object global(main.attr("__dict__"));
    boost::python::object result = boost::python::exec_file("E:\\python2.py", global, global);
    boost::python::object foo = global["foo"];
    if(!foo.is_none())
    {
        boost::python::object pyo(boost::shared_ptr<Test>(new Test())); // compile error
        foo(pyo);
    }
    return 0;
}

python2.py:

def foo(o):
    o.f()

How to pass c++ object to foo? I know swig can do that, but boost::python?

jean
  • 2,825
  • 2
  • 35
  • 72
  • possible duplicate of [Boost-python How to pass a c++ class instance to a python class](http://stackoverflow.com/questions/5055443/boost-python-how-to-pass-a-c-class-instance-to-a-python-class) – Daniel Fischer Feb 01 '12 at 00:22

2 Answers2

3

Solved.

class Test
{
public:
    void f()
    {
        std::cout<<"sss"<<std::endl;
    }
};
//==========add this============
BOOST_PYTHON_MODULE(hello)
{
    boost::python::class_<Test>("Test")
        .def("f", &Test::f)
    ;
}
//===============================
int main()
{
    Py_Initialize();
//==========add this============
    inithello();
//===============================
    boost::python::object main = boost::python::import("__main__");
    boost::python::object global(main.attr("__dict__"));
    boost::python::object result = boost::python::exec_file("E:\\python2.py", global, global);
    boost::python::object foo = global["foo"];
    if(!foo.is_none())
    {
        boost::shared_ptr<Test> o(new Test);
        foo(boost::python::ptr(o.get()));
    }
    return 0;
}

another topic

Community
  • 1
  • 1
jean
  • 2,825
  • 2
  • 35
  • 72
2

You need to expose your Test type to Python, as shown here: http://wiki.python.org/moin/boost.python/HowTo

James Hopkin
  • 13,797
  • 1
  • 42
  • 71