java使用jni调用c++动态库函数.
步骤:
1.编写java测试代码如下:
1 public class CallNativeDemo {
2 native void func();
3
4 native double add(double a, double b);
5
6 public static void main(String[] args) {
7 System.loadLibrary("Main");
8 CallNativeDemo callNativeDemo = new CallNativeDemo();
9 callNativeDemo.func();
10 System.out.println(callNativeDemo.add(1,2));
11 }
12 }
2. 使用javac 对代码进行编译:
javac CallNativeDemo.java
3.使用javah 生成CallNativeDemo.h头文件.
javah -cp . CallNativeDemo
生成的代码如下:
1 /* DO NOT EDIT THIS FILE - it is machine generated */
2 #include <jni.h>
3 /* Header for class CallNativeDemo */
4
5 #ifndef _Included_CallNativeDemo
6 #define _Included_CallNativeDemo
7 #ifdef __cplusplus
8 extern "C" {
9 #endif
10 /*
11 * Class: CallNativeDemo
12 * Method: func
13 * Signature: ()V
14 */
15 JNIEXPORT void JNICALL Java_CallNativeDemo_func
16 (JNIEnv *, jobject);
17
18 /*
19 * Class: CallNativeDemo
20 * Method: add
21 * Signature: (DD)D
22 */
23 JNIEXPORT jdouble JNICALL Java_CallNativeDemo_add
24 (JNIEnv *, jobject, jdouble, jdouble);
25
26 #ifdef __cplusplus
27 }
28 #endif
29 #endif
4.编写Main.cpp文件,如果使用的是.c文件,去掉extern "C"{}
1 #include <jni.h>
2 #include <stdio.h>
3 /*
4 * Class: CallNativeDemo
5 * Method: func
6 * Signature: ()V
7 */
8 extern "C"{
9 JNIEXPORT void JNICALL Java_CallNativeDemo_func
10 (JNIEnv *env, jobject job){
11 printf("hello world! by java and C++\n");
12 }
13
14 /*
15 * Class: CallNativeDemo
16 * Method: add
17 * Signature: (II)V
18 */
19 JNIEXPORT jdouble JNICALL Java_CallNativeDemo_add
20 (JNIEnv *env, jobject job, jdouble a, jdouble b){
21
22 return a+b;
23 }
24 }
5.使用locate/find 查询jdk位置.
locate jdk
6.编写Makefile文件.
1 #makefile
2
3 .SUFFIXES: .o.cpp
4 .PHONY: clean
5 .PHONY: start
6
7
8 JDKLIB =/home/gongxijun/java/jdk1.7.0_40/include
9 CC =g++
10 SRC =Main.cpp
11 OBJS =$(SRC:.cpp =.o)
12 OS = libMain.so
13
14 .PHONY: start
15 start: $(OBJS)
16 $(CC) -shared -fpic -I $(JDKLIB) -I $(JDKLIB)/linux -o $(OS) $(OBJS)
17 .o.cpp:$(SRC)
18 $(CC) -g -Wall $@ -c $<
19 .PHONY: clean
20 clean:
21 rm -f $(OBJS)
7.使用make 编译Makefile文件,生成.so动态库.
make Makefile 或者直接 make
8.运行java程序.
java -cp . -Djava.library.path=. CallNativeDemo
8.1结果如下:
hello world! by java and C++
3.0