Java calls local C language methods via JNI

zhaozj2021-02-16  71

http://blog.9cbs.net/chensheng913/archive/2004/07/09/37867.aspx

Java is very popular with its cross-platform features, but it is due to its cross-platform purpose, making it very little internal contacts and local machines, constrained its functions. One way to solve the Java to local operations is JNI. Java calls the local method through the JNI, and the local method is stored in the form of a library file (on the Windows platform is a DLL file form, which is the form of SO files on the UNIX machine). By calling the internal method of the local library file, Java can implement close contact with the local machine, call the interface method of the system level. Brief introduction and application is as follows: 1. Work you need to do in Java In the Java program, you first need to declare the name of the library called in the class, as follows: static {system.loadLibrary ("Goodluck");} Here, the library The extension name can not be written, is DLL or SO, which is determined by the system. It also needs to make a local statement on the method to be called, the keyword is Native. And only need to be declared without the need for a specific implementation. As follows: Public Native Static Void Set (INT i); public native static int get (); then compile the Java program file, generate a Class, use the javah command, JNI will generate a header file of C / C . For example, the program Testdll.java, the content is: public class testdll {static {system.loadlibrary ("Goodluck");} public native static int get (); public native static void set (int i); public static void main (String " ] args) {testdll test = new testdll (); test.set (10); system.out.println (TEST.GET ());}} Compiles it with Javac Testdll.java to generate TestDLL.CLASS. Use Javah TestDLL, you will generate a TestDLL.h file in the current directory, which needs to be called to generate the required library files by the C / C program. Second, the work you need to do in C / C is required for generated .h header file, C / C , is to implement it. Then compile the connection to the library file. By copying the library file to the path to the Java program, you can call the functionality implemented by C / C with Java. Connect an example.

转载请注明原文地址:https://www.9cbs.com/read-16777.html

New Post(0)