doi: 10.14355/spr.2016.05.003 Study on Programming by Combining Java with C++ Based on JNI Tan Qingquan 1, Luo Huachun* 2, Jiang Lianyan 3, Bo Tao 4, Liu Qun 5, Liu Bo 6 Earthquake Administration of Beijing Municipality, No.28 Suzhou Street, Haidian District, Beijing, P.R.China * Corespondent author. He is the chief engineer of Beijing seismic fortification management office. 1 tanqq@bjseis.cn; * 2 luohc@bjseis.cn; 3 jiangly@bjseis.cn; 4 botao@bjseis.cn; 5 liuqun@bjseis.cn; 6 baronliu@bjseis.cn Abstract Java is more and more widely used in software developing field, because of its unique characteristics. However, Java does not work as well as C++ language on some occasions. It is significant to program by combining Java with C++. In this paper, programming by combining Java with C++ based on JNI(Java Native Interface) technology on Windows platform is discussed. The key issues include passing parameters, calling C++ DLLs in Java, calling Java methods in C++, handling exceptions, and so on. In the end, a sample application is presented. Keywords JNI; Java; C++; Combined Programming Introduction Nowadays, Java has been widely used in the field of software development (especially in the field of Web programming). Because Java not only has good cross-platform portability advantage, but also has many characteristics that other programming languages cannot compare with. For example: easy to achieve security programming, easy to realize multi-threaded programming, easy to implement network applications, and so on. However, there is no perfect programming language, Java has many advantages; at the same time, there are some shortcomings: on the one hand, the running efficiency of the code is relatively low. While carrying out certain audio or image processing, complex scientific computing, Java is not the best choice; on the other hand, if the application needs to access certain specific system characteristics or devices, Java will be very cumbersome, and may even be impossible to achieve. But these deficiencies happen to be the advantages of C++. In addition, for applications or libraries that have been implemented with C++, the cost-effective way is to call directly in Java, rather than to rewrite the program. Therefore, it is significant to program by combining Java with C++. Fortunately, the JNI (Java Native Interface) defines a standard naming and calling criteria, so that Java methods can be combined with C++ methods seamlessly. Currently, some of the literature discussed JNI programming, but were basically limited to some specific application examples. This paper will comprehensively study the combined programming of Java and C++ based on JNI, and discuss the key technologies and precautions. In this paper, the C++ methods are implemented on Visual C++ developing platform. Finally, a sample application with source code is achieved and presented by combining Java with C++. Review on JNI JNI is a part of the JDK (Java Development Kit), and JNI provides Java programming interfaces of calling native methods. Therefore, based on JNI, Java code, which is running in the virtual machine, may call C/C++/assembly language code or class libraries. Using APIs provided by JNI, Java virtual machine may be embed in a local application, and all operations on the Java classes or objects can almost all be achieved in the native methods. As a result, seamless integration of Java code with C++ code will be realized. The function of JNI can be expressed in Fig. 1. 14
Signal Processing Research (SPR) Volume 5, 2016 www.seipub.org/spr FIG. 1 SCHEMATIC DIAGRAM OF JNI FUNCTION Implementation on Java and C++ Combined Programming Based on JNI Passing Parameters While programming with Java and C++, it is often needed to pass parameters values. The premise is to establish the mapping relationship between data types. For Java basic types, JNI defines a direct mapping relationship with C++ types, as shown in Table 1. These mapping types are defined in the file of jni.h. Therefore, the including statement of jni.h file will be automatically added to the local C++ header file, which is generated by javah command. The reference types in Java would be accessed by an interface pointer of JNIEnv type as the entry in C++, which will be discussed in following sections. Call C++ DLLs in Java TABLE 1 BASIC TYPES MAPPING BETWEEN JAVA AND C++ Java type C++ type storage byte boolean jboolean 1(unsigned) byte jbyte 1 char jchar 2(unsigned) short jshort 2 int jint 4 float jfloat 4 long jlong 8 double jdouble 8 void void 0 Based on the JNI specification, the DLL files implemented by C++ can be directly called in Java. These are the main steps: Write Java classes codes, implement the statement for native methods and variables, load native shared libraries. Compile the Java classes, generate byte code (*.class). Generate the native method header files (*.h) using javah command. Include the header files in C++ to achieve native method. Compile and link to generate DLL files. Call the native methods defined in DLL files in the Java program. If the native method is nativefun(), the shared library is nativevc.dll, the following Java code is needed in step 1: public native void nativefun( ); static { System.loadLibrary("nativeVC"); } Methods declared by keyword native are native methods, which are declared in Java class, without 15
implementation codes. While loading a library file, the extension is unnecessary. It s *.DLL file in Windows system, and *.SO file in Linux system. The system will automatically make a choice. Moreover, this library file should be placed under the directory, which the system will automatically search for. For example, in windows system, the current path and directories defined by environment variable PATH are valid. According to the native methods declared in Java class, the according methods will be obtained in C/C++ header file generated by javah command. Naming rules of the native method in this header file is as follows: Java[_package name]_class name_method name[ function signature]. The package name and function signature are optional. If the native method is declared in a packaged Java class, the package name will be added to the C/C++ native method. If the native method is declared as overloaded function, the function signature is necessary in C/C++ native method. This is automatically completed while compiling by javah. User cannot change the name of the native method, otherwise there will be an exception when the native method is called in Java program. Call Java Methods in C++ Using JNI, almost all of the original operations on the class or object in Java can be implemented in native methods. To create, check and update Java objects in native method, the following policies are generally adopted: first, get access to the class; then get members ID of the class, and finally get access to the member variables or functions according to the class object or ID number. Two types of parameters are automatically added to the native method statement generated by javah: JNIEnv* and jobject (jclass). The first parameter is an interface pointer of JNIEnv type, which points to a function table. Each item of the table corresponds to a JNI function pointer. As a result, the native method can achieve the operations on the class or object located in the Java virtual machine through the JNI functions. If the native method is declared as a static method in the Java, the second parameter type is jclass, which defines a reference to the Java class. In general, jobject is used to represent a reference to a Java instance object, equivalent to the pointer of this in C++. Handling Exceptions JNI provides a set of functions to handle the exception while calling JNI functions. While calling a JNI function, if an exception occurs, it must be disposed promptly. Otherwise, the Java Virtual Machine (JVM) will crash by calling other JNI functions. Generally, the exception is captured and processed by the following steps: First, determine whether an exception occurs by using ExceptionOccurred() function; secondly, take the corresponding treatment according to the abnormal position, or display the exception details by using ExceptionDescribe() function; finally, eliminate the current exception information before calling other JNI functions by using ExceptionClear() function. Java Programming Combined with Other Languages JNI provides an interface for combined programming between Java and C/C++, but Java cannot directly establish communication with VB, Delphi and other programming languages. Developers accustomed to using VB, Delphi and other programming language can implement combined programming with Java by the following method: first, implement the functions or algorithms in DLL files by VB or Delphi; then, achieve Java and C++ combined programming, and call the DLL files in C++ native methods. thus, JNI and C++ language build a bridge for combined programming of Java and other languages, as shown in Fig. 2. Sample Program FIG. 2 SCHEMATIC DIAGRAM OF COMBINED PROGRAMMING OF JAVA AND OTHER LANGUAGES The functionalities of the program are designed as follows: define a string str_java in Java, call C++ native methods in Java, pass the parameter of str_java and display the value of str_java in C ++; conversely, define a string str_vc in C++, call the member function of Java class in C++, pass the parameter of str_vc and display the value of str_vc in Java. The calling procedure is shown in Fig. 3, and the compilation and output results are shown in Fig. 4. 16
Signal Processing Research (SPR) Volume 5, 2016 www.seipub.org/spr FIG. 3 THE CALLING PROCEDURE OF SAMPLE PROGRAM FIG. 4 THE COMPILATION AND OUTPUT RESULTS OF SAMPLE PROGRAM Conclusions In addition to NI technology, there are many other solutions to achieve Java and other languages combined programming, such as, JRI(Java Runtime Interface), J/Direct, RNI(Raw Native Interface), Java/COM integration and CORBA(Common Object Request Broker Architecture), and so on. JNI is the most convenient and common way to use, because JNI is a part of JDK. By using JNI, the combined programing of Java and C++ achieved seamlessly, realizing their complementary advantages. As a result, there are more probabilities to solve some of the complex issues. In real applications, the key points include passing parameters, calling JNI functions and handling exceptions, and so on. Java is cross-platform and portable programing language, but the native code combined with Java is not portable. On different platforms, the native codes must be correspondingly modified and recompiled. In addition, it is easy to make mistakes while calling Java functions in native methods, which reduces the reliability and security of the program. Although the combined programming achieves stronger functionalities, the portability, stability and security of Java will be correspondingly reduced. In real applications, it must be given full consideration in order to achieve better application effect. ACKNOWLEDGMENT This work is financially supported by Beijing Natural Science Foundation (8164068), Project of Science for Earthquake Resilience (XH16001, XH15001Y, and XH12002Y), Policy Research Project of China Earthquake Administration (CEA-ZC/2-04-01/2016), and Science & Technology Project of Beijing Earthquake Administration (QN08).. REFERENCES [1] Cay S. Horstmann, and Gary Cornell. Core Java 2 Volume II - Advanced Features (Seventh Edition). published by Prentice Hall, 2004. 17
[2] Implementing the Java Native Interface to Harden Native Code. Accessed May 25, 2016. http://www.oracle.com/technetwork/tutorials/jni-2547567.html. [3] DONG Wei-wei. Application of JNI technology in the network interaction. Electronic Design Engineering, 24(6),125-127(2016).(in Chinese) [4] XIANG Mo-jun. Using JNI to Establish Communication between Java and C++. Computer Era, 27(12),56-57,( 2009). (in Chinese) [5] REN Jun-wei, and LIN Dong-dai. Research of Platform Independent Programming Using JNI Technology. Application Research of Computers, 22(7),180-184,(2005). (in Chinese) [6] ZHAO Nan, and HE Guang-yu. Application of JNI Technology on Platform-Independent Power Automatic System. Computer Engineering & applications, 41(17),203-206,(2005). (in Chinese) [7] WANG Yin-jiang, and LING Li. Application of JNI in Improving Efficiency of Security and Encryption System. Computer Engineering, 30(12),99-101,(2004). (in Chinese) [8] MA Jun-fei. Access system process in Java by JNI technology. Computer Systems & Applications,18(2),46-49,(2005).(in Chinese) [9] FU Jun. Discuss on Application of JNI Technology in Embedded Software Development. Microcontrollers & Embedded Systems, 5(7),12-14,(2005). (in Chinese) [10] TAN Qing-quan, BI Jian-tao, and LIU Qun, Implementation on web-oriented cutting algorithm of remote sensing images based on Java and C+. Computer Systems & Applications, 19(1):185-189, (2010).(in Chinese) Qingquan Tan is now a senior engineer of Beijing Earthquake Administration. He received his PHD degree in Cartography and Geographic Information System from Chinese Academy of Sciences in 2008. His research interests include spatial information technology, information management system, and earthquake Huachun Luo is now a associate professor of Beijing Earthquake Administration. He received his MS degree in Geological Structure from Changchun College of Geology in 1998. His research interests include Seismology & Geology, and earthquake Lianyan Jiang is now a senior engineer of Beijing Earthquake Administration. Her research interests focus on earthquake Tao Bo is now an engineer of Beijing Earthquake Administration. Her research interests focus on earthquake emergency & rescue. Qun Liu is now a associate professor of Beijing Earthquake Administration. Her research interests focus on earthquake Bo Liu is now an engineer of Beijing Earthquake Administration. His research interests focus on earthquake emergency & rescue. 18