通过boost::python将C++对象传递给python函数

pass C++ object to python function by boost::python

本文关键字:python 函数 C++ boost 通过 对象      更新时间:2023-10-16

我想在c++应用程序中使用嵌入式python,并调用python脚本中定义的函数。函数的参数是一个c++对象。查看我的代码:

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()

如何将c++对象传递给foo?我知道swig可以做到,但是boost::python?

已解决。

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;
}

另一个主题

您需要将测试类型公开给Python,如下所示:http://wiki.python.org/moin/boost.python/HowTo