通过SWIG处理Java中的C ++exception
我正在尝试使用SWIG将C ++类包装到Java类中。 这个C ++类有一个抛出exception的方法。
我有三个目标,目前没有一个目标正在发生,尽管我按照我的理解遵循了手册:
- 要让Java类在引发C ++的方法上声明
throws
- 获取SWIG生成的Exception类以扩展
java.lang.Exception
- 在生成的SWIG类中重写
Exception.getMessage()
。
似乎问题的根源似乎没有应用我的类型typemap
,因为上述情况都不会发生。 我做错了什么?
最小的例子如下。 C ++不必编译,我只对生成的Java感兴趣。 exception的类是无关紧要的,下面的代码使用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 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运行它时,exception类不会扩展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在他们申请的课程首次出现时需要看到这些类型地图。