9
我試圖使用SWIG將C++類包裝到Java類中。這個C++類有一個拋出異常的方法。通過SWIG處理Java中的C++異常
我有三個目標,其中沒有一個當前正在發生的事情,雖然我按照說明書按我的理解:
- 獲取Java類上拋出C++
- 方法聲明
throws <exceptiontype>
使SWIG生成的Exception類延伸java.lang.Exception
- 覆蓋生成的SWIG類中的
Exception.getMessage()
。
似乎問題的根源似乎是我的typemap
沒有被應用,因爲以上都沒有發生。我做錯了什麼?
最小的例子如下。 C++不必編譯,我只對生成的Java感興趣。異常的類是不相關的,下面的代碼僅僅是因爲文檔使用它而使用IOException。所有代碼適於由實施例這裏:
- http://www.swig.org/Doc1.3/Java.html#typemap_attributes
- http://www.swig.org/Doc1.3/Java.html#exception_typemap
C++頭文件(test.h):
#include <string>
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();
}
%}
當使用SWIFT 2.0.4與swig -c++ -verbose -java test.i
一起運行時,異常類不會擴展java.lang.Exception
,也不會有任何Java方法聲明throws
。
令人難以置信的令人沮喪。謝謝! –