Search code examples
c++exceptionswigextend

Swig applying %exception directive on %extend methods


I am trying to apply an exception catch handler to a method I added to a class with the %extend directive (but with no success).

My Simple Test.h File:

namespace Test {
  class TestClass
  {
    int method1()
    {
      throw MyException();
    }
  }
}

My Swig File:

%module Test

%{
#include Test.h
%}

%extend Test::TestClass {
  int method2()
  {
    throw MyException();
  }
}

%exception {
  try {
    $action
  } catch (MyException& e) {
    // do something
  }
}

%include "Test.h"

When I compile this swig file, the wrapper for method1 is generated with the exception handler but the wrapper for method2 is generated without the exception handler (I also tried to all the variants of full method name declaration and alot of other attempts with no success).

Is there a way to add the %exception directive to extended method in Swig?


Solution

  • Swap the order of the %extend and %exception directives around in your interface. The order you apply them in is important which allows you to selectively include and exclude things from being modified.