class HelloJNI { native void printHello(); // 本地方法 native void printString(String str); // 本地方法 static { System.loadLibrary("hellojni"); } // java中的静态块用于加载c/c++编写的动态库 (window下是hellojni.dll,linux下是hellojni.so) public static void main(String args[]) { HelloJNI myJNI = new HelloJNI(); // 调用本地方法(实际调用了c语言编写的本地函数) myJNI.printHello(); // 调用本地方法,对应的框架层会通过jni调用c/c++编写的对应接口 myJNI.printString("hello, this is a jni call!"); } }
javac HelloJNI.java javah HelloJNI
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class HelloJNI */ #ifndef _Included_HelloJNI #define _Included_HelloJNI #ifdef __cplusplus extern "C" { #endif /* * Class: HelloJNI * Method: printHello * Signature: ()V */ JNIEXPORT void JNICALL Java_HelloJNI_printHello (JNIEnv *, jobject); /* * Class: HelloJNI * Method: printString * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_HelloJNI_printString (JNIEnv *, jobject, jstring); #ifdef __cplusplus } #endif #endif说明:
java类型 | java本地类型 | 占用内存大小 |
byte |
jbyte | 1 |
short | jshort | 2 |
int | jint | 4 |
long | jlong | 8 |
float
|
jfloat
|
4
|
double
|
jdouble
|
8
|
char
|
jchar
|
2
|
boolean
|
jboolean
|
1
|
类 | Jclass | |
对象 | Jobject | |
String | Jstring |
最下面三种是引用类型,还有其他几种,可参考http://java.sun.com/docs/books/jni
#include "HelloJNI.h" #include <stdio.h> /* * Class: HelloJNI * Method: printHello * Signature: ()V */ JNIEXPORT void JNICALL Java_HelloJNI_printHello (JNIEnv *env, jobject obj) { printf("hello, world!\n"); return; } /* * Class: HelloJNI * Method: printString * Signature: (Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_HelloJNI_printString (JNIEnv *env, jobject obj, jstring string) { const char *str = (*env)->GetStringUTFChars(env, string, 0); printf("%s!\n", str); return; }
cl -I"C:\Program Files\Java\jdk1.7.0\include" -I"C:\Program Files\Java\jdk1.7.0\include\win32" -LD hellojni.c -Fehellojni.dll