Boost.Python: defining a constructor outside the class

Given the class:

class TCurrency {
    TCurrency();
    TCurrency(long);
    TCurrency(const std::string);
    ...
};

Wrapped using Boost.Python:

class_<TCurrency>( "TCurrency" )
    .def( init<long> )
    .def( init<const std::string&> )
    ...
    ;

Is it possible to create a factory method that appears as a constructor in Python:

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

Such as in python:

bar = TCurrency(foo)
+5
source share
2 answers

You can use make_constructor(untested):

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

class_<TCurrency>( "TCurrency" )
    .def( "__init__", boost::python::make_constructor( &TCurrency_from_Foo) )
;

The argument to make_constructor is any functor that returns a pointer [1] to the wrapped class.

[1] In fact, the function should return the type of the pointer holder, so if your pointer holder boost::shared_ptr, the function should return boost :: shared_ptr instead of the raw pointer.

+12
source

- init_python_object , . : class_t boost::noncopyable and no_init.

0

All Articles