2、Java调用C语言(JNative法)

这个方法也是挺麻烦的……

一、下载JNative.jar,把它放在你jdk下的\jre\lib\ext目录下

二、在 F:\MinGW\JNative 新建 Test.java:

 

public class Test  {        

  public static void main(String[] args) throws NativeException, IllegalAccessException {

 

     // 例1  

     JNative n1 = new JNative("test.dll", "add"); 

 

     n1.setRetVal(Type.INT);          

     n1.setParameter(0, 11);  //C语言add函数的第一个参数是11

     n1.setParameter(1, 9);  //C语言add函数的第二个参数是9   

     n1.invoke();   //执行           

 

     int re1 = Integer.parseInt(n1.getRetVal());  //获取返回结果   

     System.out.println("例1:addresult = "+re1);

 

 

     

     // 例2  

    JNative n2= new JNative("test.dll", "addArray");

    int len=3;  

     //定义一个int指针p1,一个int占4个字节,(4 * len)可以理解成有len个int。若是double则(8 * len),以此类推   

    Pointer p1 = new Pointer(MemoryBlockFactory.createMemoryBlock(4 * len));   

    Pointer p2 = new Pointer(MemoryBlockFactory.createMemoryBlock(4 * len));   

    Pointer p3 = new Pointer(MemoryBlockFactory.createMemoryBlock(4 * len));       

 

    p1.setIntAt(0, 11);p1.setIntAt(4, 18);p1.setIntAt(8, 21);   

    p2.setIntAt(0, 44);p2.setIntAt(4, 56);p2.setIntAt(8, 100);

    n2.setRetVal(Type.VOID);   

    n2.setParameter(0, p1);   

    n2.setParameter(1, p2);   

    n2.setParameter(2, p3);   

    n2.setParameter(3, len);   

    n2.invoke();

    for (int i = 0; i < len; i++) {    

      System.out.println("例2:addArray"+(i+1)+" = "+p3.getAsInt(i*4));   

    }     

 

    p1.dispose();   

    p2.dispose();   

    p3.dispose();  

 

 

      

    // 例3   

    JNative n3 = new JNative("test.dll", "stringFun");   

    n3.setRetVal(Type.STRING);

 

    String inputString = "kun";   

    String outputString = "";   

    Pointer p4 = Pointer.createPointerFromString(inputString);   

    Pointer p5 = Pointer.createPointerFromString(outputString); 

 

    n3.setParameter(0, p4);   

    n3.setParameter(1, p5);   

    n3.invoke();     

    System.out.println("例3:outputString = "+n3.getRetVal());      p4.dispose();   p5.dispose();    

    }

}

 

三、再新建一个 test.c:

 

#include <stdio.h>

#include <malloc.h>

int add(int a, int b) {  

  return (a + b);

}

void addArray(int *a,int *b,int *c,int len) {  

  int i;  

  for(i=0;i<len;i++) {   

    c[i]=a[i]+b[i];  

  }

}

char* stringFun(char *str1,char *str2) {  

  printf("例3:intputString = %s\n",str1);

  str2 = (char*)malloc(sizeof(char)*17);

  str2 = "HG-U133_Plus_2.0";

  return str2;

}

 

四、生成dll:

 

方法一:如果安装了MinGW

f: cd MinGW/JNative

gcc -Wall -shared test.c -o test.dll

javac Test.java

java Test

 

这时目录下新生成了JNativeCpp.dll、test.dll、Test.class

 

方法二:如果安装了Rtools(注意:我是Win7系统)

f: cd MinGW/JNative

R CMD SHLIB test.c

javac Test.java

java Test

 

这时目录下新生成了JNativeCpp.dll、test.dll、test.o、Test.class

 

结果:

 

posted @ 2015-03-23 11:17  洗浄  阅读(818)  评论(0编辑  收藏  举报