I'm porting a Python extension module written in C++ from Boost.Python to SWIG.
The C++ code defines an abstract class X with a static factory method
class X {
public:
static X* create(const char* descr);
...
};
The factory method returns a pointer to an instance of some derived class.
With Boost.Python you can wrap the C++ class X in a Python class X that has an
__init__(self, descr)
method that calls X::create. In fact, it is done as follows:
namespace bp = boost::python;
bp::class_<X>("X", boost::no_init)
.def("__init__", bp::make_constructor(&X::create))
...
Is there a way of doing the same thing with SWIG?
As suggested, it is better to use __new__ for controlling how a class is created. In SWIG, you should create an interface (.i) file that looks as follows:
%extend X {
static X * __new__(const char *desc) { return create(desc); }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With