Wrapping C++ struct template in SWIG

784 views Asked by At

I have a C++ code that wraps an existing Object with a probability as follows:

template< typename Object > struct Roll
{
    Object object;          
    double probability; 

    Roll( Object p, double s )
        : object( p )
        , probability( s )
    { }
}

Later, this will be defined in the same .h file as:

typedef Roll< Color > RollColor;

There's instruction around how to wrap a C++ struct with primitive type in SWIG but this one has something to do with the template also, so I don't know how to wrap it properly in my interface file. Do you have any idea how can I do this ? Thank you very much.

1

There are 1 answers

2
R Sahu On

In the .i file, use:

%template(RollColor) Roll<Color>;

More info at http://www.swig.org/Doc1.3/Python.html#Python_nn26.

Assuming you have the template defined in roll.h and Color is defined in color.h, you will need to use:

%{
   #include "roll.h"
   #include "color.h"
%}

#include "roll.h"
#include "color.h"

%template(RollColor) Roll<Color>;

Update, in response to OP's comment

You can use:

%template(RollColors) std::vector<Roll<Color>>;

However, you will need to implement a default constructor in Roll first. Without that you can't create a std::vector of Roll<T>s.

You can use

%template(RollColors) std::vector<RollColor>;

only if you have a C++ typedef.

%{
   #include "roll.h"
   #include "color.h"
   typedef Roll<Color> RollColor;
%}