Why doesn't ITK SwigInterface/igenerator.py just use SWIG `%template`?

In order to create a Python wrapping for ITK, Wrapping/Generators/SwigInterface/igenerator.py generates “itk*.i” files for all wrapped ITK types. For example for itk::Size<unsigned int>, it generates a file named <Bin>\ITK\Wrapping\Typedefs\itkSize.i. This file contains class definitions for itkSize2, itkSize3, and itkSize4, for example (simplified):

class itkSize2 {
  public:
    ...
    itkSize2();
    itkSize2(itkSize2 const & arg0);
    itkSize2 & operator=(itkSize2 const & arg0);
    ~itkSize2();
};

These classes (itkSize2, itkSize3, and itkSize4) are then passed to SWIG, in order to wrap them, if I understand correctly.

Is there a specific reason why we do it like that? Instead of passing those classes to SWIG, would it be an option to directly pass the itk::Size<unsigned int> template to SWIG? SWIG does support templates, for example:

%template(itkSize2) itk::Size<2>;
%template(itkSize3) itk::Size<3>;
%template(itkSize4) itk::Size<4>;

So why don’t we use the SWIG %template keyword?

See also the discussion I had with @blowekamp at How to wrap a static constexpr data member (an integer value), for Python? · swig/swig · Discussion #3088 · GitHub

We do use %template for STL types in pyBase.i.

To use %template, it may be challenging to implement the rest of the functionality in pyBase.i and similar functionality.

To go in that direction, we would want to transition ITK to more STL functionality and behavior and then use SWIG’s built-in support for what was implemented manually. For example,

  • itk::LightObjectstd::shared_ptr
  • itk::Sizestd::array

etc.

1 Like

Thanks Matt! So we use %template for STL types, but not for ITK types. Why not for ITK types?

ITK types have their own ownership semantics and mechanisms, code to behave like Python sequences when appropriate, etc.

2 Likes

An advantage of using SWIG %template would be automatic wrapping of static constexpr data members. For example, the static data member itk::Size::Dimension would then be wrapped automatically into Python as a Python class variable. It seems to me that it is technically possible to use %template for “simple” ITK types like itk::Size and itk::Point. But anyway, it may still be a lot of work :person_shrugging: