我正在尝试使用SWIG将C 类包装到Java类中。此类C类具有引发异常的方法。
我有三个目标,尽管据我所知遵循了手册,但目前没有一个目标:
要使Java类throws 在C ++中引发的方法上声明
要获取SWIG生成的Exception类以进行扩展 java.lang.Exception
Exception.getMessage()在生成的SWIG类中重写。
似乎问题的根源似乎typemap没有应用我的,因为以上均未发生。我做错了什么?
最小的示例如下。C
++不必编译,我只对生成的Java感兴趣。异常的类无关紧要,并且下面的代码使用IOException仅仅是因为文档中使用了它。所有代码均从此处的示例改编而成:
C ++头文件(test.h):
#include
class CustomException {
private:
std::string message;
public:
CustomException(const std::string& message) : message(msg) {}
~CustomException() {}
std::string what() {
return message;
}
};
class Test {
public:
Test() {}
~Test() {}
void something() throw(CustomException) {};
};
SWIG .i文件:
%module TestModule
%{
#include "test.h"
%}
%include "std_string.i" // for std::string typemaps
%include "test.h"
// Allow C++ exceptions to be handled in Java
%typemap(throws, throws="java.io.IOException") CustomException {
jclass excep = jenv->FindClass("java/io/IOException");
if (excep)
jenv->ThrowNew(excep, $1.what());
return $null;
}
// Force the CustomException Java class to extend java.lang.Exception
%typemap(javabase) CustomException "java.lang.Exception";
// Override getMessage()
%typemap(javacode) CustomException %{
public String getMessage() {
return what();
}
%}
swig -c++ -verbose -java test.i与SWIG 2.0.4
一起运行时,异常类不会扩展,java.lang.Exception并且所有Java方法都没有throws声明。