Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap a C++ factory method in a Python __init__ function using SWIG

Tags:

c++

python

swig

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?

like image 311
Johan Råde Avatar asked Feb 07 '26 02:02

Johan Råde


1 Answers

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); }
};
like image 91
user1202136 Avatar answered Feb 09 '26 15:02

user1202136



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!