1、示例介绍
示例涉及到:
1.1、Java调用C程序
1.2、Java向C程序传入int类型参数,int类型的数组参数,C程序向Java程序返回整型参数
int类型参数在不同平台下的字节长度不同。在Java向C传入数组参数时,C程序需要申请数组空间,在程序结束后要手动释放数组空间。
1.3、Java向C程序传入String类型参数,C程序向Java程序返回字符串参数
在C环境中,char长度为8位。而java中的char的编码为Unicode(JDK1.3之前)和UTF8(JDK1.4之后)。因此Java向C传入参数、C向Java返回参数都需要对字符串进行转换处理。
2、运行环境配置
2.1、编写源代码
2.1.1、编译java文件,生成class文件:javac jni.Sample2.java,或者进入jni文件夹中,运行javac Sample2.java
2.1.2、根据class文件生成C语言的头文件:javah jni.Sample2,生成jni_Sample2.h
2.1.3、编写Sample2.c
如果class文件是在一个包中,那么生成的h文件中的方法前缀也是有包名和方法名组成的。在后面的调用过程中要保证class文件所在的包没有改变,如果改变class文件的位置,就需要重新生成h头文件和动态库文件。
2.2、生成so文件
gcc Sample2.c –shared –o libsample2.so
在linux系统中,so文件一般是以lib开始的。一定要将linux下的动态库命名成libxxx.so的形式,"xxx"是你在System.loadLibrary("xxx")中用到的加载库名称。否则会出现
Exception in thread "main" java.lang.UnsatisfiedLinkError: no sample2 in java.library.path
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at org.jdesktop.jdic.tray.internal.impl.DisplayThread.(Unknown Source)
at org.jdesktop.jdic.tray.internal.impl.WinSystemTrayService.(Unknown Source)
at org.jdesktop.jdic.tray.internal.impl.ServiceManagerStub.getService(Unknown Source)
at org.jdesktop.jdic.tray.internal.ServiceManager.getService(Unknown Source)
at org.jdesktop.jdic.tray.SystemTray.(Unknown Source)
at livechat.function.TrayTest.main(TrayTest.java:67)
Exception in thread "Thread-2" java.lang.UnsatisfiedLinkError: removeIcon
at org.jdesktop.jdic.tray.internal.impl.WinTrayIconService.removeIcon(Native Method)
at org.jdesktop.jdic.tray.internal.impl.WinTrayIconService.removeAllIcons(Unknown Source)
at org.jdesktop.jdic.tray.internal.impl.WinTrayIconService$1.run(Unknown Source)
这样的异常,即使在环境完全配置成功,这个异常也是无法消除的。(另外的解决办法为:
System.load ("/app/jnidemo/libsample2.so"),使用绝对路径。)
2.3、配置环境与运行
Java程序通过JNI调用C语言生成的so文件。因此需要将so文件放入java运行环境中的library中。方法有两种:
export LD_LIBRARY_PATH=.,设置LD_LIBRARY_PATH为当前文件夹
然后运行:java jni.Sample2
方法二:
直接运行:java –Djava.library.path=. jni.Sample2
3、代码
http://download.csdn.net/source/1064489