标签:machine library ptr null get def style export usr
1、什么是JNI:
在C中实现这个方法,在方法内部输出“Hello World",然后再回到Java中进行调用。分为以下步骤:
建立一个类:JNIDemo
public class JNIDemo { static { /* 1. load */ System.loadLibrary("native"); /* libnative.so */ } public native static void hello(); public native static int hello(String str, int []a); public static void main(String[] args) { System.out.println("JNIDemo"); /* 1. load */ System.loadLibrary("native"); /* libnative.so */ /* 2. map hello java<-->c c_hello */ /* 3. call */ hello(); } }
编译java
$ javac JNIDemo.java
gen jiu java wenjian cahn sheng tou wenjian xie C wenjian
$ javah -jni JNIDemo
Output JNIDemo.h
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class JNIDemo */ #ifndef _Included_JNIDemo #define _Included_JNIDemo #ifdef __cplusplus extern "C" { #endif /* * Class: JNIDemo * Method: hello * Signature: ()V */ JNIEXPORT void JNICALL Java_JNIDemo_hello__ (JNIEnv *, jclass); /* * Class: JNIDemo * Method: hello * Signature: (Ljava/lang/String;[I)I */ JNIEXPORT jint JNICALL Java_JNIDemo_hello__Ljava_lang_String_2_3I (JNIEnv *, jclass, jstring, jintArray); #ifdef __cplusplus } #endif #endif
new native.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 cls) { printf("Hello, world!\n"); } static const JNINativeMethod methods[] = { {"hello", "()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, "JNIDemo"); if (cls == NULL) { return JNI_ERR; } /* 2. map hello java<-->c c_hello */ if((*env)->RegisterNatives(env, cls, methods, 1) < 0) return JNI_ERR; return JNI_VERSION_1_4; }
指定头文件路径 -I /usr/lib/jvm/java-1.7.0-openjdk-amd64/include/ 编译产生库
$ gcc -I /usr/lib/jvm/java-1.7.0-openjdk-amd64/include/ -fPIC -shared -o libnative.so native.c
运行
$ java JNIDemo
结果
JNIDemo
Hello, world!
标签:machine library ptr null get def style export usr
原文地址:http://www.cnblogs.com/CZM-/p/7635484.html