Java's method of invoking C language through JNI

Source: Internet
Author: User

Java, which is popular with its cross-platform features, and because of its cross-platform purpose, makes it less powerful and its internal connections to local machines, constraining its functionality.

One way to solve Java's local operations is JNI.

Java invokes the local method through JNI, and the local method is stored in the form of a library file (in the form of a DLL file on a Windows platform and a so file form on a UNIX machine). By invoking the internal method of the local library file, Java can implement close contact with the local machine and invoke the system-level interface methods.

Simple introduction and application are as follows:

One, Java needs to do the work

In a Java program, you first need to declare the name of the library called in the class, as follows:

static {
System.loadLibrary(“goodluck”);
}

Here, the extension of the library name can not be written out, whether it is a DLL or so, by the system itself to judge.

You also need to make a local declaration of the method that will be invoked, with the keyword native. And only need to declare, and not need to implement specifically. As follows:

Public native static void set (int i);

public native static int get ();

Then you compile the Java program file, generate class, and then use the Javah command, and JNI will generate the header file for C + +.

For example, 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());
}
}

Compiling it with Javac Testdll.java generates Testdll.class.

With Javah Testdll, the testdll.h file will be generated in the current directory, which needs to be called by C + + program to generate the required library files.

Related Article

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.