'Swigging templated class with complex signature

I am trying to swig some c++ code to python. Unfortunately, I am running into some issues with class templating. Here is a base.h class:

#include <Eigen/Dense>

template<int dim>
class Base {
public:
    Base();
    virtual ~Base() {}

    virtual const Eigen::Matrix<double, dim, dim> Method(const Eigen::Matrix<double, dim, dim>& F,
        const Eigen::Matrix<double, dim, dim>& dF) const = 0;
    virtual const Eigen::Matrix<double, dim * dim, dim * dim> Method(const Eigen::Matrix<double, dim, dim>& F) const = 0;
};

And a child class:

#include <Eigen/Dense>
#include "base.h"

template<int dim>
class Child : public Base<dim> {
public:
    const Eigen::Matrix<double, dim, dim> Method(const Eigen::Matrix<double, dim, dim>& F,
        const Eigen::Matrix<double, dim, dim>& dF) const override;
    const Eigen::Matrix<double, dim * dim, dim * dim> Method(
        const Eigen::Matrix<double, dim, dim>& F) const override;
};

I am trying to swig these into 2D and 3D versions of the code (dim=2 or dim=3) using my test.i file:

%module test
%{
#include "base.h"
#include "child.h"
%}

%exception {
    try {
        $action
    } catch (const std::runtime_error& e) {
        PyErr_SetString(PyExc_RuntimeError, const_cast<char*>(e.what()));
        SWIG_fail;
    } catch (...) {
        PyErr_SetString(PyExc_RuntimeError, "Unknown error.");
        SWIG_fail;
    }
}

%include <std_array.i>
%include <std_vector.i>
%include <std_string.i>
%include <std_map.i>
%include "base.h"
%include "child.h"

namespace std {
    %template(StdRealArray2d) array<real, 2>;
    %template(StdRealArray3d) array<real, 3>;
    %template(StdIntArray3d) array<int, 3>;
    %template(StdIntArray4d) array<int, 4>;
    %template(StdIntArray8d) array<int, 8>;
    %template(StdRealVector) vector<real>;
    %template(StdIntVector) vector<int>;
    %template(StdRealMatrix) vector<vector<real>>;
    %template(StdMap) map<string, real>;
}

%template(Base2d) Base<2>;
%template(Base3d) Base<3>;

%template(Child2d) Child<2>;
%template(Child3d) Child<3>;

Whenever I try to build a project using this, swig really seems to be choking on the dim * dim in one of the overloaded functions, which throws errors when I try to build. How can I get around this? This is working with code I inherited and is part of a big project, so I can't re-structure too much.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source