Step 1: Write the Java Code
Create a Java class namedHelloWorldthat declares a native method. This class also includes amainmethod that creates aHelloWorldobject and calls the native method.
Step 2: Compile the Java Code
Use
javac to compile the Java code that you wrote in
Step 1.
Step 3: Create the .h File
Usejavahto create a JNI-style header file (a.hfile) from theHelloWorldclass. The header file provides a function signature for the implementation of the native methoddisplayHelloWorld.
Step 4: Write the Native Method Implementation
Write the implementation for the native method in a native language (such as ANSI C) source file. The implementation will be a regular function that's integrated with your Java class.
Step 5: Create a Shared Library
Use the C compiler to compile the.hfile and the.cfile that you created in Steps 3 and 4 into a shared library. In Windows 95/NT terminology, a shared library is called a dynamically loadable library (DLL).
Step 6: Run the Program
And finally, use java, the Java interpreter, to run the program.
package jni;
public class HelloWorld {
public native void displayHelloWorld();
static {
//System.loadLibrary("hello");
Runtime.getRuntime().loadLibrary("hello");
}
public static void main(String[] args) {
new HelloWorld().displayHelloWorld();
}
}
#include <jni.h>
#include "jni_HelloWorld.h"
#include <stdio.h>
JNIEXPORT void JNICALL
Java_jni_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj)
{
printf("Hello world!\n");
return;
}
本文介绍了一个简单的JNI示例,通过创建一个名为HelloWorld的Java类并声明本地方法,然后使用javac编译Java代码,利用javah生成JNI头文件,用C语言实现本地方法,并编译为共享库。最后通过Java解释器运行程序。
657

被折叠的 条评论
为什么被折叠?



