在java中创建jni,都是通过一些命令,创建一些基本文件,然后在VS C++中,创建工程,导入那些文件,比较繁琐,不容易管理,而且c++中出了异常的话,java也不好处理。基于以上原因,我们可以使用JunC++ ion来使得整个过程自动化。
JunC++ion 创建JNI过程
首先将所有的native方法的class放入一个单独的java工程里,在ANT文件中,配置好,运行后,可以生成一个c++工程。接下来只需在xxxuserImpl文件中,做参数转换和调用native方法实现,最后编译,链接生成dll。在Java中,这些参数不使用java基本类型而使用包装类型为好。在参数转换时,就完全可以采用标准c++类型来处理了。JunC++ion对java的基本类型,采用c++做了重写。如:java.lang.String,重写为:Java::lang::string.
总结:快速创建C++工程,便于管理,可以异常控制等等。
Here's what you would do in Java:
- design a Java type that exposes the desired API to Java applications and internally uses native methods to delegate to the C++ side.
- run the
javah
tool to generate C declarations for for the required native methods. - implement all the native methods in a combination of C, JNI, and your own C++ code.
Here's what the same development process looks like when you're using JunC++ion:
- design a Java type that exposes the desired API to Java applications and internally uses native methods to delegate to the C++ side.
- run the code generator to generate delegating implementations for the required native methods.
- implement all the native methods in a combination of generated C++ proxy classes and your own C++ code.
The obviousness of the answer depends on your familiarity with JNI and on the scale of your integration problem. JNI is typically considered a rather unattractive integration technology because it's so error-prone and hard to use. When you're implementing native methods using JNI, you rarely have the luxury of only using your own code in the implementation. Much more frequently, you need to access elements on the Java side or create Java instances as return values, forcing you to call back into Java via JNI. Coding JNI by hand is a shortcut to an unstable appliation because it's trivially easy (even for an experienced JNI developer) to leak references or make other mistakes that will eventually lead to a hard-to-debug application failure. If you add C++ with its ability to throw exceptions to the mix, you almost certainly have a catastrophe that's just waiting to happen because your Java process will not tolerate a C++ exception thrown from within a native method.