【问题标题】:Wrap all swig-generated methods in try { } catch在 try { } catch 中包装所有 swig 生成的方法
【发布时间】:2021-11-28 10:53:28
【问题描述】:

我有带有 C++ 库的 Android 项目。使用 Swig 工具生成的 JNI 类。

一些 C++ 方法会抛出 std 异常,例如std::invalid_argument

对于所有标准异常都存在相同的 Java 异常(例如 C++ std::invalid_argument = java.lang.IllegalArgumentException)。但是当 throw std::invalid_argument 在 C++ 中时,应用程序崩溃了。

如何说 SWIG 将所有生成的方法包装在 try-catch 块中以处理 Java 异常而不是 C++ 异常?为了能够在我的 java 代码中处理这个异常。

是否有可能使它“在一行中”或者我需要为所有方法显式地制作包装器? 感谢您的帮助。

我的痛饮脚本: 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"

【问题讨论】:

标签: java android android-ndk swig


【解决方案1】:

好的,问题是在swig-script.i 文件中,所有#include 都在%exception 定义之后。

工作示例:

%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"

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    相关资源
    最近更新 更多