You begin by writing the following program in the Java programming language.
The program defines a class named HelloWorld that contains a native method,
print.
There are two differences between the declaration of a native method such as print and thedeclaration of regular methods in the Java programming language.
1、本地方法一定要有native这个修饰语modifier。
2、这个本地方法不是它自己的class里面实现的,是通过另外一种语言实现的。
3、在调用这个本地方法之前,java虚拟机会事先自动加载对应的“静态本地库”,这样也保证了本地库在本地方法被调用之前事先加载好。
上一篇文章有讲过如何使用javac javah生成相应的文件,如.class以及JNI-style header file。
我们详细看一下javah -jni生成的函数原型prototype。we will no list the general header file in its entirety here。
我们先看它的最重要部分:函数的原型和模型是如何的:
JNIEXPORT void JNICALLJava_HelloWorld_print (JNIEnv *, jobject);
对应本地方法里面的print();注意:这里原来是不带参数的哦。
1、The first argument for every native method implementation is a JNIEnv interface pointer.
2、The second argument is a reference to the HelloWorld object itself (sort of like the “this” pointer in C++).
We will discuss how to use the JNIEnv interface pointer and the jobject arguments later in this book, but this simple example ignores both arguments.
The program defines a class named HelloWorld that contains a native method,
print.
class HelloWorld {
private native void print();
public static void main(String[] args) {
new HelloWorld().print();
}
static {
System.loadLibrary("HelloWorld");
}
}
There are two differences between the declaration of a native method such as print and thedeclaration of regular methods in the Java programming language.
1、本地方法一定要有native这个修饰语modifier。
2、这个本地方法不是它自己的class里面实现的,是通过另外一种语言实现的。
3、在调用这个本地方法之前,java虚拟机会事先自动加载对应的“静态本地库”,这样也保证了本地库在本地方法被调用之前事先加载好。
上一篇文章有讲过如何使用javac javah生成相应的文件,如.class以及JNI-style header file。
我们详细看一下javah -jni生成的函数原型prototype。we will no list the general header file in its entirety here。
我们先看它的最重要部分:函数的原型和模型是如何的:
JNIEXPORT void JNICALLJava_HelloWorld_print (JNIEnv *, jobject);
对应本地方法里面的print();注意:这里原来是不带参数的哦。
1、The first argument for every native method implementation is a JNIEnv interface pointer.
2、The second argument is a reference to the HelloWorld object itself (sort of like the “this” pointer in C++).
We will discuss how to use the JNIEnv interface pointer and the jobject arguments later in this book, but this simple example ignores both arguments.