How to add code into Swig wrapper for C++ class constructor, targeting Ruby

Ok i know it’s a big title … but it describes the problem.

Lets say that you have a C++ class and you wrap it using swig. Now you decide to inject some code of your own into the constructor wrapper. If you try defining a typemap(out) you will not succeed. Instead the way to do it is this:

%module test


Β #include “MyClass.h”



%feature(“ref”) MyClass ” Here between the quotes add your code ”


%include “MyClass.h”


Well that’s it. Let me note, in case you are not aware, that the above code should go inside the *.i file that will be parsed by swig. You have now managed adding extra code into the _wrap_new_MyClass function that wraps the costructor of your class. Keep in mind that the above solution goes if you are targeting Ruby. Perhaps for other scripting languages you can add code into contructor wrapper function using %typemap(out) MyClass*, but that doesn’t work for Ruby. The above case is valid for swigwin-1.3.27 that i use currently.

Keep coding.