现在让我们向Python暴露一个C ++类。
考虑我们要向Python暴露的C ++类/结构:
struct World
{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
我们可以通过编写相应的Boost.Python C ++ Wrapper将它暴露给Python:
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}
在这里,我们编写了一个C ++类包装器,它公开了成员函数greet和set。现在,在将模块构建为共享库之后,我们可以使用Python中的World类。
这是一个Python会话示例:
>>> import hello
>>> planet = hello.World()
>>> planet.set('howdy')
>>> planet.greet()
'howdy'