首页 > 代码库 > 用C如何编写给java使用的动态库

用C如何编写给java使用的动态库

//1:编写[CallC.java],用于生成C头文件,C包含此头文件编写方法

 1 //CallC.java 2     public class CallC 3     { 4         static 5         { 6             System.loadLibrary("useC");  //注册库文件名、C生成的库文件在windows下为useC.dll linux下生成为libuseC.so 7          } 8         //声明的本地方法,可以写多个 9         public  staitc native int useC(int flag,String path,String action);10            11     }


//2:执行[javac CallC.java] ,生成CallC.class

//3:执行[javah -classpath . CallC] 生成CallC.h ,制定classpath为当前路径

//4:编写[CallC.cpp]  拷贝jin.h和jin_md.h到代码目录 修改CallC.h 里面头文件, 如果系统有这些头文件则不需处理

 1 //CallC.cpp 2 #include "CallC.h" 3  4 #include <stdio.h> 5 #include <stdlib.h> 6  7 JNIEXPORT jint JNICALL Java_CallC_useC 8   (JNIEnv * env , jclass arg, jint jmethods , jstring jname, jstring jparam) 9 {10     unsigned char *name = NULL;11     unsigned char *param = NULL;12     int methods = jmethods;13     char cmd_buf[256] = {0};14     int nRet = 0 ;15     16     if(jparam)17     {18         name =  (unsigned char *)env->GetStringUTFChars( jname, JNI_FALSE );19     }20     if(jparam)21     {22         param = (unsigned char *)env->GetStringUTFChars( jparam, JNI_FALSE );23     }24     25      printf("name = %s\n",name); 26    printf("param = %s\n",param); 27    printf("methods = %d\n" , methods);28    29     30     31     switch(jmethods)32     {33         case 1:34             {35                 sprintf(cmd_buf,"%s %s" ,name ,  param);36                 printf("%s\n" , cmd_buf);37                 system(cmd_buf);38                 break;39             }40         default :41             {42                 nRet = 1;43                 break;44             }45     }46 47   48    49      // 通知虚拟机本地代码不再需要通过 str 访问 Java 字符串。50   env->ReleaseStringUTFChars( jname, (const char *)name ); 51   env->ReleaseStringUTFChars( jparam, (const char *)param );52     return 0;  53 54 }

 

//5:执行[g++ -Wl,--kill-at -shared -fPIC -o  useC.dll CallC.cpp] 编译代码,生成useC.dll  

//6:编写[UseC.java]测试代码

1 public class UseC2 {3     public static void main(String argv[])4     {5           int result = CallC.useC(1 , "dir" , "/a:-d");    6           System.out.print(result);7     }8 }

//7:执行[javac -cp . UseC.java]编译java测试源码  

//8:执行[java -Djava_library.path=. -cp . UseC]运行java程序测试动态库

//参考资料 

windows下安装gcc编译环境  http://tieba.baidu.com/p/2826016538

linux下 java JNI调用C语言动态链接库 - JonnyWei的专  http://blog.csdn.net/xiaojianpitt/article/details/5652223

java.lang.UnsatisfiedLinkError解决方法汇集    http://blog.csdn.net/niuxinlong/article/details/4176612