实现相应的头文件, 并编译为动态链接库(windows下是.dll, linux下是.so)
编写带有native方法的Java类
public class Sample { public native int intMethod(int n); public native boolean booleanMethod(boolean bool); public native String stringMethod(String text); public native int intArrayMethod(int[] intArray); }
javac Sample.java
使用javah生成头文件, 生成Sample.h文件
javah Sample
通过Sample.cpp文件实现Sample.h文件中定义的native方法
#include "Sample.h" #include <string> JNIEXPORT jint JNICALL Java_Sample_intMethod (JNIEnv *env, jobject obj, jint num) { return num * num; } JNIEXPORT jboolean JNICALL Java_Sample_booleanMethod (JNIEnv *env, jobject obj, jboolean boolean) { return !boolean; } JNIEXPORT jstring JNICALL Java_Sample_stringMethod (JNIEnv *env, jobject obj, jstring string) { const char* str = env->GetStringUTFChars(string, 0); char cap[128]; strcpy(cap, str); env->ReleaseStringUTFChars(string, 0); return env->NewStringUTF(strupr(cap)); } JNIEXPORT jint JNICALL Java_Sample_intArrayMethod (JNIEnv *env, jobject obj, jintArray array) { int i, sum = 0; jsize len = env->GetArrayLength(array); jint *body = env->GetIntArrayElements(array, 0); for (i = 0; i < len; ++i) { sum += body[i]; } env->ReleaseIntArrayElements(array, body, 0); return sum; }
g++ -I /usr/java/jdk1.7.0_21/include/ -I /usr/java/jdk1.7.0_21/include/linux/ -fPIC -c Sample.cpp
生成动态库文件,如果使用到其它对象文件(.o文件)以及动态连接库,则在Sample.o后面增加相应的参数
g++ -shared -Wl,-soname,libSample.so.1 -o libSample.so.1.0 Sample.o
设置动态库路径或拷贝到系统目录(/usr/lib或/usr/lib64)
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
测试
public class TestSample { public static void main(String[] args) { System.loadLibrary("Sample"); Sample sample = new Sample(); int square = sample.intMethod(5); boolean bool = sample.booleanMethod(true); String text = sample.stringMethod("Java"); int sum = sample.intArrayMethod(new int[]{1,2,3,4,5,8,13}); System.out.println("intMethod: " + square); System.out.println("booleanMethod: " + bool); System.out.println("stringMethod: " + text); System.out.println("intArrayMethod: " + sum); } }
参考文献:
使用JNI进行Java与C/C++语言混合编程(1)--在Java中调用C/C++本地库, 在Java中调用C/C++本地库