通过SWIG处理Java中的C++异常

Mar*_*oot 9 c++ java swig

我正在尝试使用SWIG将C++类包装到Java类中.这个C++类有一个抛出异常的方法.

我有三个目标,虽然我按照我的理解遵循了手册,但目前都没有这个目标:

  • 让Java类声明throws <exceptiontype>抛出C++的方法
  • 获取SWIG生成的Exception类进行扩展 java.lang.Exception
  • Exception.getMessage()在生成的SWIG类中覆盖.

似乎问题的根源似乎是我的typemaps未被应用,因为上述情况都没有发生.我做错了什么?

最小的例子如下.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) {};
};
Run Code Online (Sandbox Code Playgroud)

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();
  }
%}
Run Code Online (Sandbox Code Playgroud)

swig -c++ -verbose -java test.i使用SWIG 2.0.4 运行时,异常类不会扩展,java.lang.Exception并且没有任何Java方法具有throws声明.

Fle*_*exo 10

当你看到这个时,你会踢自己.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"
Run Code Online (Sandbox Code Playgroud)

%include "test.h"后,你想申请到班test.h,而不是之前的typemaps.SWIG在他们申请的课程首次出现时需要看到这些类型地图.