---
title: "java 调用 .so 文件"
author: "djkin"
date: "2015-01-02T21:03:34Z"
tags: []
categories: ["移动开发"]
slug: "java-so"
draft: false
lastmod: "2015-01-02T21:03:33Z"
id: 2171747
url: "https://djkin.iteye.com/blog/2171747"
---

我的测试过程，请参考。  
Java代码（Test.java）：

Java code[?](http://bbs.csdn.net/topics/320210465#clipboardWindow "源码")

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[?](http://bbs.csdn.net/topics/320210465#clipboardWindow "源码")

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[?](http://bbs.csdn.net/topics/320210465#clipboardWindow "源码")

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