簡體   English   中英

通過SWIG處理Java中的C ++異常

[英]Handling C++ exceptions in Java via SWIG

我正在嘗試使用SWIG將C ++類包裝到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();
  }
%}

當使用swig -c++ -verbose -java test.i和SWIG 2.0.4運行它時,異常類不會擴展java.lang.Exception並且沒有任何Java方法具有throws聲明。

當你看到這個時,你會踢自己。 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"

%include "test.h" 您希望應用於test.h中的類的類型映射之后,而不是之前。 SWIG在他們申請的課程首次出現時需要看到這些類型地圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM