Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Python: Defining a constructor outside a class

Given a class:

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

Wrapped with 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 that in python:

bar = TCurrency(foo)
like image 950
James Emerton Avatar asked Dec 02 '09 19:12

James Emerton


1 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] Actually, the function must return a the pointer holder type, so if your pointer holder is boost::shared_ptr, the function should return a boost::shared_ptr instead of a raw pointer.

like image 88
Bruno Oliveira Avatar answered Sep 29 '22 22:09

Bruno Oliveira