Is it possible to wrap both for regular exception and SEH exceptions

86 Views Asked by At

I have a native C++ library and a SWIG-generated wrapper for C#. the .i file contains an %exception that wraps all the $actions inside regular try/catchblocks to convert exceptions to our desired target C# exceptions using SWIG_CSharpSetPendingExceptionCustom. Something like this

%exception {
    try
    {
        $action
    }
    catch(const our::Exception& exc)
    {
        //blahblah
        SWIG_CSharpSetPendingExceptionCustom(/*blah*/);
        return $null;
    }
    catch(const std::exception& exc)
    {
        /*blah*/
    }       
    catch(...)
    {
        /*blah*/
    }
}

This works great, all regular C++ exceptions are nicely wrapped and forwarded to C#.

But what I also need is to wrap all my function with the SEH __try/__except blocks in order to catch potential access violations and whatnot and print the native stack trace. Something like

%exception {
    __try
    {
        $action
    }   
    __except(print_my_stack_trace(GetExceptionInformation()))
    {       
    }   
}

Unfortunately it is not allowed to combine regular try with SEH __try in one function in any way. So if my library has an arbitrary function myclass::f, what I would like to achieve is for SWIG to first create a f_temp function whose body will contain try/catch, then the true wrapper of f that would call f_temp wrapped with __try/__catch. The result for f would look something like

void SWIGSTDCALL CSharp_blah_myclass_f_TEMP__(void * jarg1) {
  myclass *arg1 = (myclass *) 0 ;
  
  arg1 = (myclass*)jarg1; 
  {
    try
    {
      (arg1)->f();
    }
    catch(const our::Exception& exc)
    {
      ...
      SWIG_CSharpSetPendingExceptionCustom(...);
      return ;
    }
    catch(const std::exception& exc)
    {
      ...
    }
}

SWIGEXPORT void SWIGSTDCALL CSharp_blah_myclass_f__(void * jarg1) {
     __try
    {
      CSharp_blah_myclass_f_TEMP__(jarg1)
    }
    __except(print_my_stack)
    {
      
    }    
}

I am thinking of resorting to writing a perl script that would manipulate the swig-generated wrapper .cpp file textually, but I first want to make sure that this is not possible to achieve with swig magic. So, can anyone think of a SWIG solution that does not involve ad-hoc manipulation of generated sources?

0

There are 0 best solutions below