Boost.Python:在类外定义构造函数

Jam*_*ton 5 constructor factory boost-python

给出一个类:

class TCurrency {
    TCurrency();
    TCurrency(long);
    TCurrency(const std::string);
    ...
};
Run Code Online (Sandbox Code Playgroud)

用Boost.Python包装:

class_<TCurrency>( "TCurrency" )
    .def( init<long> )
    .def( init<const std::string&> )
    ...
    ;
Run Code Online (Sandbox Code Playgroud)

是否可以创建在Python中显示为构造函数的工厂方法:

TCurrency TCurrency_from_Foo( const Foo& ) { return TCurrency(); }
Run Code Online (Sandbox Code Playgroud)

这样在python中:

bar = TCurrency(foo)
Run Code Online (Sandbox Code Playgroud)

Bru*_*ira 12

你可以使用make_constructor(未经测试):

TCurrency* TCurrency_from_Foo( const Foo& ) { return new TCurrency(); }

class_<TCurrency>( "TCurrency" )
    .def( "__init__", boost::python::make_constructor( &TCurrency_from_Foo) )
;
Run Code Online (Sandbox Code Playgroud)

make_constructor的参数是任何将指针[1]返回到包装类的函子.

[1]实际上,函数必须返回一个指针持有者类型,所以如果你的指针持有者boost::shared_ptr,函数应该返回一个boost :: shared_ptr而不是一个原始指针.