繁体   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