Linux环境下java识别so中的方法
时间: 2016-04-20来源:开源中国
前景提要
HDC调试需求开发(15万预算),能者速来!>>>
最近在看java加载so的相关内容,并写了个简单的测试程序,代码如下,但是最终没有获取到结果,不知道错误原因,现将整个的测试程序贴出,希望大家帮忙看看,谢谢。
(1)JNI:用于生成头文件的java类

package com; public class JNIC_SO { static { try { System.loadLibrary("libJNIC_SO" ); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); } } public native static int funMyTestAdd(int x,int y); public native static String funMyPrintf(); }
(2)编译生成的头文件(.h)



JNIEXPORT jint JNICALL Java_com_JNIC_1SO_funMyTestAdd (JNIEnv *, jclass, jint , jint ); /* * Class: com_JNIC_SO * Method: funMyPrintf * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_JNIC_1SO_funMyPrintf (JNIEnv *, jclass);
(3)编写c程序,用于生成待调用的so文件



/* * c_so.h */ #ifndef C_SO_H_ #define C_SO_H_ int funMyTestAdd(int x,int y); char* funMyPrintf(); #endif /* C_SO_H_ */ /* *c_so.c */ #include "c_so.h" int funMyTestAdd(int x,int y){ return x+y; } char* funMyPrintf(){ return "This is a test for sprintting a string!"; } /* * libJNIC_SO.c */ #include "c_so.h" #include "com_JNIC_SO.h" #include "/opt/JDK1.7/jdk1.7.0_75/include/jni.h" #include "/opt/JDK1.7/jdk1.7.0_75/include/jawt.h" #include "/opt/JDK1.7/jdk1.7.0_75/include/linux/jni_md.h" JNIEXPORT jint JNICALL Java_com_JNIC_1SO_funMyTestAdd (JNIEnv *evn, jclass obj, jint x, jint y){ //int x =0,y=0; return funMyTestAdd(x,y); } JNIEXPORT jstring JNICALL Java_com_JNIC_1SO_funMyPrintf (JNIEnv *evn, jclass obj){ return funMyPrintf();//暂时先不处理 }
(4)通过命令生成SO文件



gcc -fPIC -g -shared -D_REENTRANT -I/opt/JDK1.7/jdk1.7.0_75/include -I/opt/JDK1.7/jdk1.7.0_75/include/linux -c *.c -o libJNIC_SO.so
(5)将生成的so文件拷贝至“/use/lib”目录下
(6)编写java调用SO测试程序
package com.znitech; public class JNIMytest { static { System.load("/usr/lib/libJNIC_SO.so"); } public native int funMyTestAdd(int x,int y); public static void main(String[] args) { JNIMytest sl = new JNIMytest(); int z = 0; try{ z = sl.funMyTestAdd(1,2); }catch(Exception ex){ System.out.println(ex.getMessage()); } System.out.print("the add result:"+z); } }



测试程序在Eclipse下的运行结果:

Exception in thread "main" java.lang.UnsatisfiedLinkError: com.znitech.JNIMytest.funMyTestAdd(II)I at com.znitech.JNIMytest.funMyTestAdd(Native Method) at com.znitech.JNIMytest.main(JNIMytest.java:15)



望大家指出有误之处,或提出更好的建议,先谢了!


科技资讯:

科技学院:

科技百科:

科技书籍:

网站大全:

软件大全:

热门排行