如何让SWIG自动为生成的JNI方法加try-catch转C++异常为Java异常
解决方案
不需要为每个方法单独编写包装器,仅需在你现有的SWIG接口文件中添加少量全局配置即可实现C++ std异常自动转Java异常的需求。
配置步骤
- 在接口文件中引入SWIG官方提供的
std_except.i库,该库已经预置了大部分标准C++异常与Java异常的映射关系,包含你提到的std::invalid_argument到java.lang.IllegalArgumentException的对应。 - 添加全局
%exception指令,让SWIG为所有生成的JNI方法自动包裹try-catch逻辑,捕获C++侧异常后转换为对应Java异常抛出。
注意:上述配置需要放在你引入自定义头文件(
cpp-dsp.h、pipeline_options.h)的代码之前,才能对所有生成的方法生效。
修改后的完整接口文件示例
%module(directors="1") CppDsp %{ #include "cpp-dsp.h" #include "pipeline_options.h" %} // 新增:引入标准异常转换库 %include "std_except.i" // 新增:全局异常捕获配置 %exception { try { $action } // 按需添加不同异常的处理分支,以下为示例 catch(const std::invalid_argument& e) { jclass exCls = jenv->FindClass("java/lang/IllegalArgumentException"); if (exCls) jenv->ThrowNew(exCls, e.what()); return $null; } catch(const std::runtime_error& e) { jclass exCls = jenv->FindClass("java/lang/RuntimeException"); if (exCls) jenv->ThrowNew(exCls, e.what()); return $null; } catch(const std::exception& e) { jclass exCls = jenv->FindClass("java/lang/Exception"); if (exCls) jenv->ThrowNew(exCls, e.what()); return $null; } } //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"
额外说明
如果你的项目中有自定义C++异常类型,只需在上述%exception块中追加对应的catch分支,指定要抛出的Java异常类即可,无需修改其他逻辑。
内容的提问来源于stack exchange,提问作者Рома Богдан
相关产品推荐
相关产品推荐

