The first step: writing Java programs
public class HelloWorld {
public native void Displayhelloworld ();
static {
System.loadlibrary ("Hello");
}
public static void Main (string[] args) throws Exception {
New HelloWorld (). Displayhelloworld ();
}
}
Notice where the Code
public native void Displayhelloworld ();
is to declare that Displayhelloworld () is a local method that needs to be implemented in JNI.
static {
System.loadlibrary ("Hello");
}
It means that the download of the file in the library implies that our following JNI program eventually needs to be packaged into Hello.dll
Step two: Compile the Java program
Javac Helloworld.java
Step three: Generate header Files
Javah-jni HelloWorld
Step Fourth: Write local implementation code
We open the third step generated by the HelloWorld.h this file, find the method declaration
jniexport void Jnicall Java_helloworld_displayhelloworld
(JNIENV *, jobject);
This is the JNI naming convention, specificallyYou can refer to the Java tutorial. Here's just the method declaration, and now we're going to implement it.
* HELLOWORLDIMP.C * *
#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>
Jniexport void Jnicall
Java_helloworld_displayhelloworld (jnienv *env, Jobject obj)
{
printf ("Hello world!\n");
Return
}
Step Fifth: Create a library file
As mentioned in the first step, Hello.dll is generated using the previously mentioned command to make a dynamic library.
Gcc-i%java_home%\include-i%java_home%\include\win32-shared-o Hello.dll helloworldimp.c
Run
Java HelloWorld
No, it's wrong.
Exception in thread "main" Java.lang.UnsatisfiedLinkError:displayHelloWorld
At Helloworld.displayhelloworld (Native method)
At Helloworld.main (helloworld.java:9)
This means that the library file has been successfully loaded, but no matching displayhelloworld is found. But we have realized this method. The original program in the call to the dynamic library, not as simple as we imagined, and different compiler practices, Windows version Java invoke JNI to follow the way the VC calls, and we use the MinGW GCC default format inconsistent. We need to adjust the parameters (note the--kill-at)
gcc-i%java_home%\include-i%java_home%\include\win32-shared-wl,--kill-at-o hello.dll helloworldimp.c
Run
Java HelloWorld
Hello world! Run successfully, great