第一步:编写、编译java程序
class HelloJNI {
native void printHello();
static {
System.loadLibrary("hellojni");
}
public static void main(String args[]) {
HelloJNI myJNI = new HelloJNI();
myJNI.printHello();
}
}
第二步:在JNI中获取成员变量或成员方法签名
# javap -s -p HelloJNI
Compiled from "HelloJNI.java"
class HelloJNI {
HelloJNI();
Signature: ()V
native void printHello();
Signature: ()V
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
static {};
Signature: ()V
}
第三步:编写C++/C程序
#include <jni.h> /* /usr/lib/jvm/java-1.7.0-openjdk-amd64/include/ */
#include <stdio.h>
#if 0
typedef struct {
char *name; /* Java里调用的函数名 */
char *signature; /* JNI字段描述符, 用来表示Java里调用的函数的参数和返回值类型 */
void *fnPtr; /* C语言实现的本地函数 */
} JNINativeMethod;
#endif
void c_hello(JNIEnv *env, jobject obj)
{
printf("Hello World!\n");
return ;
}
static const JNINativeMethod methods[] = {
{"printHello", "()V", (void *)c_hello},
};
/* System.loadLibrary */
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *jvm, void *reserved)
{
JNIEnv *env;
jclass cls;
if ((*jvm)->GetEnv(jvm, (void **)&env, JNI_VERSION_1_4)) {
return JNI_ERR; /* JNI version not supported */
}
cls = (*env)->FindClass(env, "HelloJNI");
if (cls == NULL) {
return JNI_ERR;
}
/* 2. map java hello <-->c c_hello */
if ((*env)->RegisterNatives(env, cls, methods, 1) < 0)
return JNI_ERR;
return JNI_VERSION_1_4;
}