版权声明:本文为博主原创文章,欢迎转载(请声明出处),私信通知即可 https://blog.csdn.net/xinqingwuji/article/details/89183738
我们之前的示例没有任何显式构造函数。由于World被声明为普通结构,因此它具有隐式默认构造函数。 Boost.Python默认公开默认构造函数,这就是我们能够编写的原因
>>> planet = hello.World()
我们可能希望用非默认构造函数包装一个类。
让我们以前面的例子为基础:
struct World
{
World(std::string msg): msg(msg) {} // added constructor
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
这次World没有默认构造函数;
当库试图公开它时,我们以前的包装代码将无法编译。我们必须告诉class_ <World>我们想要公开的构造函数。
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World", init<std::string>())
.def("greet", &World::greet)
.def("set", &World::set)
;
}
init <std :: string>()公开了接受std :: string的构造函数(在Python中,构造函数拼写为“”__init__“”)。
我们可以通过将更多init <...>传递给def()成员函数来公开其他构造函数。比方说,我们有另一个World构造函数接受两个双精度:
class_<World>("World", init<std::string>())
.def(init<double, double>())
.def("greet", &World::greet)
.def("set", &World::set)
;
另一方面,如果我们不希望暴露任何构造函数,我们可以使用no_init代替:
class_<Abstract>("Abstract", no_init)
这实际上添加了一个__init__方法,它总是引发Python RuntimeError异常。
源代码:https://github.com/Lxxing/PythonStudy