[FIXED] Wrap all swig-generated methods in try { } catch

Issue

I have Android project with C++ library. JNI classes generated with Swig tool.

Some C++ method throws std exceptions, e.g. std::invalid_argument

For all std exception exist same Java-exception (e.g. C++ std::invalid_argument = java.lang.IllegalArgumentException). But when throw std::invalid_argument in C++, application crash.

How to say SWIG to wrap all generated methods in try-catch block to trhow Java-exceptions instead of C++ exceptions? To be able to handle this exception inside my java-code.

Is it possible to make it "in one line" or i need to make wrappers for all methods explicitly?
Thanks for help.

My swig-script:
run_swig.sh

%module(directors="1") CppDsp

// Anything in the following section is added verbatim to the .cxx wrapper file

%{
#include "cpp-dsp.h"
#include "pipeline_options.h"
%}

//define converters from C++ double pointer to Kotlin double-array
%include carrays.i
%array_functions( double, double_array )
//define converters from C++ long pointer to Kotlin long-array
%array_functions( long long, long_long_array )
%array_functions( signed char, byte_array )

// Process our C++ file (only the public section)

%include "cpp-dsp.h"
%include "pipeline_options.h"

Solution

Ok, the problem was that in swig-script.i file, all #include was after %exception definition.

Working example:

%module(directors="1") CppDsp

// Anything in the following section is added verbatim to the .cxx wrapper file

%{
#include "cpp-dsp.h"
#include "pipeline_options.h"
%}

//define converters from C++ double pointer to Kotlin double-array
%include carrays.i
%array_functions( double, double_array )
//define converters from C++ long pointer to Kotlin long-array
%array_functions( long long, long_long_array )
%array_functions( signed char, byte_array )

%exception {
    try {
        $action
    }
    catch (const std::exception& e) {
        SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, e.what());
        return $null;
    }
}

// Process our C++ file (only the public section)
// ENSURE, THAT INCLUDES ARE ON THE LAST LINES
%include "cpp-dsp.h"
%include "pipeline_options.h"

Answered By – Рома Богдан

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published