ITeye博客

java 调用 .so 文件

djkin · 2015-01-02 21:03 · 学习记录 · 移动开发 · Markdown

我的测试过程,请参考。
Java代码(Test.java):

Java code?

1

2

3

4

5

6

7

8

9

10

11

12

class Test {

static {

System.load("/lib/libtestjni.so");

}

 

public static native int get();

 

public static void main(String[] args) {

Test t = new Test();

System.out.println(t.get());

}

}

调用javah生成的C头文件(Test.h)

C/C++ code?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class Test */

 

#ifndef _Included_Test

#define _Included_Test

#ifdef __cplusplus

extern "C" {

#endif

/*

* Class:     Test

* Method:    get

* Signature: ()I

*/

JNIEXPORT jint JNICALL Java_Test_get

(JNIEnv *, jclass);

 

#ifdef __cplusplus

}

#endif

#endif

自定义的C源程序(Test.c)

C/C++ code?

1

2

3

4

5

6

7

8

9

10

11

#include<dlfcn.h>

#include<stdio.h>

#include<stdlib.h>

 

#include "Test.h"

 

JNIEXPORT jint JNICALL Java_Test_get

(JNIEnv* env, jobject obj) {

  

return 10;

}

我使用的是OpenJDK 6.0,使用以下命令编译Test.c,生成Test.o

gcc -Wall -c -o Test.o Test.c -I/usr/lib/jvm/java-6-openjdk/include -I/usr/lib/jvm/java-6-openjdk/include/linux

查看Test.o的内容,使用以下命令

nm Test.o

看到的内容如下:

00000000 T Java_Test_get

用以下命令生成so文件

gcc -Wall -rdynamic -shared -o libtestjni.so Test.o

查看libtestjni.so的内容,使用以下命令

nm libtestjni.so

看到的内容如下:

000003ec T Java_Test_get
00001f20 a _DYNAMIC
00001ff4 a _GLOBAL_OFFSET_TABLE_
         w _Jv_RegisterClasses
00001f10 d __CTOR_END__
00001f0c d __CTOR_LIST__
00001f18 d __DTOR_END__
00001f14 d __DTOR_LIST__
00000454 r __FRAME_END__
00001f1c d __JCR_END__
00001f1c d __JCR_LIST__
0000200c A __bss_start
         w __cxa_finalize@@GLIBC_2.1.3
00000400 t __do_global_ctors_aux
00000330 t __do_global_dtors_aux
00002008 d __dso_handle
         w __gmon_start__
000003e7 t __i686.get_pc_thunk.bx
0000200c A _edata
00002014 A _end
00000438 T _fini
000002cc T _init
0000200c b completed.6625
00002010 b dtor_idx.6627
000003b0 t frame_dummy

将libtestjni.so拷贝到/lib/

sudo cp libtestjni.so /lib

调用Test.class

java Test

看到的内容是

10

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。