2012-12-21 34 views
9

我試圖使用SWIG將C++類包裝到Java類中。這個C++類有一個拋出異常的方法。通過SWIG處理Java中的C++異常

我有三個目標,其中沒有一個當前正在發生的事情,雖然我按照說明書按我的理解:

  • 獲取Java類上拋出C++
  • 方法聲明throws <exceptiontype>使SWIG生成的Exception類延伸java.lang.Exception
  • 覆蓋生成的SWIG類中的Exception.getMessage()

似乎問題的根源似乎是我的typemap沒有被應用,因爲以上都沒有發生。我做錯了什麼?

最小的例子如下。 C++不必編譯,我只對生成的Java感興趣。異常的類是不相關的,下面的代碼僅僅是因爲文檔使用它而使用IOException。所有代碼適於由實施例這裏:

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

回答

9

當你看到這件事時,你會踢自己。您的SWIG接口的固定版本爲:

%module TestModule 
%{ 
#include "test.h" 
%} 

%include "std_string.i" // for std::string typemaps 

// 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(); 
    } 
%} 

%include "test.h" 

I.e. %include "test.h"之後您想要應用於test.h類中的類型映射,而不是之前。 SWIG在他們申請的課程第一次出現時就需要看到類型圖。

+0

令人難以置信的令人沮喪。謝謝! –