Use JNI technology to Call DLL for Java programs

Source: Internet
Author: User

Java's cross-platform features are favored by Java programmers, but it is precisely because of its cross-platform purpose that it has little internal connection with local machines, it greatly limits its functions. For example, communication with some hardware devices usually requires a lot of effort to design the process and write code to manage the device ports, in addition, some hardware interfaces provided by equipment manufacturers have been encapsulated and processed, and Java programs cannot be directly used to communicate with devices through ports, in this case, we have to consider using Java programs to call third-party programs that are better at dealing with the system. JDK starting from version 1.1 provides the technical standard for solving this problem: JNI technology.
JNI is the abbreviation of Java Native Interface (Java Local interface). Compared with Java programs, JNI directly runs on the operating system and interacts with the operating system. JNI has been released as part of the standard platform since JDK 1.1. in the early days of JNI's appearance, it was designed for Java programs and locally compiled languages, especially the interoperability between C and C ++, later, it was extended to interact with programs written in languages other than C and C ++, such as Delphi programs.
Although JNI technology enhances the performance and functions of Java programs, it also damages the cross-platform advantages of Java and affects the portability and security of programs, for example, Java pointer security cannot be guaranteed because other languages (such as C/C ++) may be able to allocate objects or occupy memory at will. however, in some cases, using JNI is acceptable or even necessary. For example, the Java program mentioned above calls the class library provided by the hardware vendor to communicate with the device, this is the case for many card reader devices on the market. when JNI is required, try to encapsulate all local methods in a single class. This class calls a single local library file and ensures that for each target operating system, you can replace this file with a version specific to the appropriate platform. In this way, you get a lot more out of JNI.
Now let's start to discuss the problem mentioned above. Generally, the device chamber provides two types of class library files, which may be included in windows. dll /. h /. lib file, and the Linux system will contain. so /. file a. Here we will only discuss how to call the DLL files compiled by C/C ++ in windows.
I call the DLL file provided by the equipment vendor A third-party DLL file. The reason for this is that JNI directly calls the DLL file compiled in C/C ++ according to its standards, this file is provided by the customer programmer according to the equipment vendor. the DLL file compiled by the methods listed in the H file is called the second-party DLL file. The DLL file actually called by the device manufacturer is the second-party DLL file. at this point, the idea of solving the problem has been generated. The big score can be divided into three steps:
1> compile a Java class that includes methods provided by the equipment vendor. the hfile has been deformed/converted and must be defined using native. note that the methods defined in the Java program do not have to have the same name/return value/parameter as the methods listed in the header file provided by the vendor, because some parameter types such as pointers cannot be simulated in Java, you only need to ensure that this method can implement the functions provided by the methods in the original DLL file;
2> write a DLL program in C/C ++ according to the JNI rules;
3> call the methods defined in the DLL program provided by the vendor in your own DLL program according to the DLL calling rules.

I used to add the IC card read/write function to a Java project. I checked a lot of information and found that I only talked about Step 2. So I had to study the rest by myself. the following three steps are used to analyze the code.

1> assume that the. h file provided by the vendor defines a method we need:
_ Int16 _ stdcall readdata (handle icdev, _ int16 offset, _ int16 Len, unsigned char * data_buffer );
A. _ int16 defines an integer that does not depend on a specific hardware or software environment and occupies 16 bits in any environment (the int type in Java is 32 bits ), this data type is a specific data type in VC ++, so the dll I made is also compiled using VC ++.
B. _ stdcall indicates that this function can be called by other programs. If the DLL compiled by VC ++ is called by a program written in other languages, the call method of the function should be declared as _ stdcall, winapi adopts this method. the default call Method for C/C ++ is _ cdecl. Therefore, when you make a DLL that can be called by a Java program, you must add the _ stdcall statement, otherwise, Type Mismatch Error will be reported during Java program execution.
C. handle icdev is a concept in the Windows operating system and belongs to a Win32 Data type. It represents the unique index of a core object in a process, not a pointer, when you know the object type represented by this index, You can forcibly convert it to this type of data.
This knowledge belongs to the Win32 Programming scope. For more detailed Win32 information, refer to relevant documents.
The original meaning of this method is to read a total of Len characters starting from the offset of a string in the memory space by using the device ID icdev generated during the initial operation of the device, stored in the memory space of the unsigned character type pointed to by data_buffer, and a 16-bit integer value is returned to indicate whether the Read Device is successful, what is really needed here is the data stored by the unsigned char * pointer pointing to the address, but there is no pointer type in Java, so you can consider defining a Java method that returns the string type, the integer value returned in the original method can also be transmitted by string type according to certain rules. Because handle is an ojbect data type in Java, it can be processed as an int type, in this way, the method definition in the Java program has been formed:
String readdata (INT icdev, int offset, int Len );
When declaring this method, you must add the native keyword to indicate that this is a Java method that communicates with the local method. For the sake of security, this method should be hidden from other classes and use the private declaration, write another public method to call it, and load the local file in this class. The final code is as follows:

Package test;

Public class linkdll
{
// Read data from the specified address
Private native string readdata (INT icdev, int offset, int Len );
Public String readdata (INT icdev, int offset, int Len)
{
Return this. readdatatemp (icdev, offset, Len );
}

Static
{
System. loadlibrary ("testdll"); // if the execution environment is Linux, The so file is loaded. If the execution environment is windows, the DLL file is loaded.
}
}

2> use the JDK javah command to generate a method definition that contains the class. h file, you can enter the root directory of the class file package (as long as it is in the path in the classpath parameter), add the package name javah test when using the javah command. linkdll. After the command is successful, a header file named test_linkdll.h is generated.
The file content is as follows:

/* Do not edit this file-it is machine generated */
# Include <JNI. h>

/* Header for class test_linkdll */
# Ifndef _ included_test_linkdll # define

Included_test_linkdll
# Ifdef _ cplusplus extern "C" {# endif
/*
* Class: test_linkdll
* Method: readdatatemp
* Signature: (iii) ljava/lang/string;
*/
Jniexport jstring jnicall java_test_linkdll_readdatatemp (jnienv *, jobject, jint );
# Ifdef _ cplusplus} # endif
# Endif

It can be seen that in order to realize the communication with the DLL file, JNI has processed according to its standard method name, parameter type, and parameter number, the jnienv */jobjtct parameters are inherent parameters of each JNI method. The javah command is responsible for adding these two parameters to each Java method according to the JNI standard. jnienv is a pointer to a special JNI data structure whose type is jnienv _. When compiled by the C ++ compiler, the jnienv _ structure is actually defined as a class, this class defines many embedded functions. By using the "->" symbol, you can easily use these functions, such:
(ENV)-> newstring (jchar * C, jint Len)
The LEN characters can be read from the address pointed to by the pointer C and encapsulated into a jstring type data.
The jchar corresponds to the char in C/C ++, The jint corresponds to the len in C/C ++, And the jstring corresponds to the string in Java. View JNI. h. You can see that these data types are the basic data types or struct that are redefined using the typedef keyword Based on the Data Type correspondence between Java and C/C ++.
The relationship is as follows:
Java local type description
Boolean jboolean C/C ++ 8-bit integer
Byte jbyte C/C ++ signed 8-bit integer
Char jchar C/C ++ unsigned 16-bit integer
Short jshort C/C ++ signed 16-bit integer
Int jint C/C ++ signed 32-bit integer
Long jlong C/C ++ signed 64-bit integer e
Float jfloat C/C ++ 32-bit floating point
Double jdouble C/C ++ 64-bit floating point type
Object jobject any Java object, or no corresponding Java type object
Class jclass Class Object
String jstring String object
Object [] jobjectarray any array of Objects
Boolean [] jbooleanarray Boolean Array
Byte [] jbytearray Bit Array
Char [] jchararray struct Array
Short [] jshortarray short integer Array
Int [] jintarray integer Array
Long [] jlongarray long integer Array
Float [] jfloatarray float Array
Double [] jdoublearray dual floating point Array
For more detailed information, see the JNI documentation.
Note: The test_linkdll.h file contains the JNI. h file;

3> Use VC ++ 6.0 to compile the testdll. dll file. The file name is consistent with the loadlibrary name in the Java class.
A> Create A Win32 dynamic-Link Library Project File Using VC ++ 6.0. Set the project name to testdll.
B> load the source code file and header file to the project using the "add fiels to project" menu. If C is used for encoding, the source code file suffix is. c. If C ++ is used for encoding, the source code file extension is. CPP, this must be clarified, because for different languages, the jnienv pointer method is different.
C> in this file, the DLL file provided by the device manufacturer is called. Generally, the device vendor provides three types of files: dll/lib/h, which are assumed to be. dll/. LIB/. h.
In this place, the call is divided into dynamic call and static call, that is, as long as the called DLL file is put under the path, and then load the Lib link file and. the H header file can be called directly. DLL method:
Load the. h file provided by the equipment supplier to this project using the "add fiels to project" menu, and include the. h file in the source code file;
Click the "Project-> Settings" menu, open the link tab, and add a. lib to the "Object/library modules" option.
The specific code is as follows:
// Read data. Note that if the C program must add * Before the variable name of jnienv when calling the JNI function, for example (* env)-> XXX, if it is a C ++ program, directly use (ENV)-> xxx

# Include <windows. h>
# Include <malloc. h>
# Include <stdio. h>
# Include <JNI. h>
# Include "test_linkdll.h"
# Include "A. H"

Jniexport jstring jnicall java_test_linkdll_readdatatemp (jnienv * ENV, jobject Jo, jint ji_icdev, jint ji_len)
{
// ************************** Basic data declaration and definition ******** **********************
Handle h_icdev = (handle) ji_icdev; // device identifier
_ Int16 i16_len = (_ int16) ji_len; // The length of the read data. The value is 3, which is a character in the hex format.
_ Int16 i16_result; // function return value
_ Int16 i16_coverresult; // return value of the character Conversion Function
Int I _temp; // The intermediate variable used for Loop
Jchar jca_result [3] = {'E', 'R', 'R'}; // This string is returned when a data read error occurs.

// Unsigned character pointer, pointing to the memory space used to store the read data string in the hex format
Unsigned char * uncp_hex_passward = (unsigned char *) malloc (i16_len );

// Unsigned character pointer, pointing to memory space storage from hex form to ASC form of data string
Unsigned char * uncp_asc_passward = (unsigned char *) malloc (i16_len * 2 );

// Java char pointer, pointing to the memory space that stores the data string read from the space where the ASC form data string is stored
Jchar * jcp_data = (jchar *) malloc (i16_len * 2 + 1 );

// Java string, which stores the string generated from the Java char array and returns it to the caller
Jstring js_data = 0;

// ********* Read three data characters in hex format to the memory space specified by uncp_hex_data **********
I16_result = readdata (h_icdev, 6, uncp_hex_data); // The prototype method provided by the equipment vendor is directly called here.

If (i16_result! = 0)
{
Printf ("card reading error.../N ");
// Call the JNI-defined method newstring (jchar *, jint) to convert the jchar string to the jstring type and return it to the Java program as the string type.
Return (ENV)-> newstring (jca_result, 3 );
}

Printf ("data read succeeded.../N ");

// *************** Convert a data string in the hex form to an ASC form ************ **
I16_coverresult = hex_asc (uncp_hex_data, uncp_asc_data, 3 );
If (i16_coverresult! = 0)
{
Printf ("character conversion error! /N ");
Return (ENV)-> newstring (jca_result, 3 );
}

// *********** Convert the data string in ASC char form to a data string in jchar form ***********
For (I _temp = 0; I _temp <i16_len; I _temp ++)
Jcp_data [I _temp] = uncp_hex_data [I _temp];

// ****************** Convert a data string in the jchar format to a Java string *********** *****
Js_data = (ENV)-> newstring (jcp_data, i16_len );

Return js_data;
}

Dynamic call. Without the Lib file, load the. dll file directly and declare the file again. The Code is as follows:
# Include <stdio. h>
# Include <windows. h>
# Include "test_linkdll.h"

// Declare a temporary method. The method name can be defined at will, but the parameters are consistent with those of the prototype method provided by the device manufacturer.
Typedef int (* readdatatemp) (INT, Int, Int, unsigned char *); // read data from a specified address

// Read data from the specified address
Jniexport jstring jnicall java_readdatatemp (jnienv * ENV, jobject Jo, jint ji_icdev, jint ji_offset, jint ji_len)
{
Int I _temp;
Int I _result;
Int I _icdev = (INT) ji_icdev;
Int I _offset = (INT) ji_offset;
Int I _len = (INT) ji_len;
Jchar jca_result [5] = {'E', 'R', 'R '};
Unsigned char * uncp_data = (unsigned char *) malloc (I _len );
Jchar * jcp_data = (jchar *) malloc (I _len );
Jstring js_data = 0;

// Hinstance is a data type similar to handle in Win32, meaning handle to an instance. It is often used to mark an app instance. the DLL is loaded into the memory space and stored as an app.

Give the instance to dllhandle for other resources.
Hinstance dllhandle;
Dllhandle = loadlibrary ("A. dll ");

// First define a declared temporary method. This temporary method is equivalent to a struct. It has the same parameter structure as the prototype method provided by the equipment vendor and can be converted to each other.
Readdatatemp readdata;

// Use the getprocaddress method of Win32 to obtain the readdata method defined in A. dll, and convert this method to a temporary method with the same structure as defined,
// In the following program, you can use this temporary method. Using this temporary method is equivalent to using the Prototype Method in A. dll.
Readdata = (readdatatemp) getprocaddress (dllhandle, "readdata ");

I _result = (* readdata) (I _icdev, I _offset, I _len, uncp_data );

If (I _result! = 0)
{
Printf ("failed to read data.../N ");
Return (ENV)-> newstring (jca_result, 3 );
}

For (I _temp = 0; I _temp <I _len; I _temp ++)
{
Jcp_data [I _temp] = uncp_data [I _temp];
}

Js_data = (ENV)-> newstring (jcp_data, I _len );

Return js_data;
}

4> the above is the complete process for a Java program to call a third-party DLL file. Of course, after the entire process is completed, you can use the Public String raddata (INT, int, INT) method. The same effect is that C/C ++ is used to call. the readdata method in the DLL file is almost the same.

Summary: JNI technology indeed improves the execution efficiency of Java programs and extends the functions of Java programs. However, it does destroy the most important advantages of Java programs: platform independence, therefore, unless JNI technology is required (mandatory), 100% pure Java programs are generally recommended. based on your own experience and some materials, list the situations where JNI technology can be used as follows:
1> You Need To directly operate the physical device without related drivers. In this case, you may need to write the driver of the device in C or even assembly language, and then call it through JNI;
2> when Java is used, a large number of mathematical operations are involved;
3> using Java will produce overhead that is hard to pay by the system, such as when a large number of network connections are required;
4> there are a large number of reusable C/C ++ code. Using JNI can reduce the development workload and avoid repeated development.
In addition, pay attention to the following points when using JNI technology:
1> due to restrictions of the Java security mechanism, do not try to publish an applet containing the localization method to the client using the JAR file;
2> pay attention to the memory management issue. Although local references are automatically released after the local method returns Java, too many local references will exhaust the memory when the VM executes the local method;
3> the JNI technology not only allows Java programs to call C/C ++ code, but also allows C/C ++ code to call Java code.

Note: A jawin open-source project called jawin allows you to directly read third-party DLL files without having to manually write a DLL file for value transfer. If you are interested, please study it. however, when I use it, it is not easy, and there are many rules and restrictions. For example, when I write a program, I can define the return value and convert the type at will. It is impossible to use this package, so my project has not started to discard it.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.