各位大虾,在java中如何调用C的代码啊,高手们给个例子啊!先谢了!

解决方案 »

  1.   

    参考core java 2 7th 第11章
      

  2.   

    http://flamingheart.blogchina.com/3864765.html
      

  3.   

    try use JNI
    jdk document里面有教程
      

  4.   

    倒 JNI知识嘛 我给个我测试过的example :
      

  5.   

    自己利用JNI的话比较复杂建议先用SWIG对C做个JAVA的包装,然后再将C生成操作系统对应的库文件,你的java中就可以轻松调用了
      

  6.   

    我前几天研究过这个问题。代码帖出来给你看看
    java 代码
    public class testdll { 
    static { 
    System.loadLibrary("CCtestdll"); 

    public native static int get(); 
    public native static void set(int i); 
    public static void main(String[] args){ 
    testdll test = new testdll(); 
    test.set(13); 
    System.out.println(test.get()); 

    }
    c++
    #include "testdll.h" 
    int i = 0; 
    JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass) { 
    return i; 

    JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint j) { 
    i = j; 
    }
      

  7.   

    public class testdll { 
    static { 
    System.loadLibrary("goodluck"); 

    public native static int get(); 
    public native static void set(int i); 
    public static void main(String[] args) { 
    testdll test = new testdll(); 
    test.set(10); 
    System.out.println(test.get()); 

    }用javac testdll.java编译它,会生成testdll.class。 
      再用javah testdll,则会在当前目录下生成testdll.h文件,这个文件需要被C/C++程序调用来生成所需的库文件。 testdll.h文件的内容: 
    /* DO NOT EDIT THIS FILE - it is machine generated */ 
    #include 
    /* Header for class testdll */ 
    #ifndef _Included_testdll 
    #define _Included_testdll 
    #ifdef __cplusplus 
    extern "C" { 
    #endif 
    /* 
    * Class: testdll 
    * Method: get 
    * Signature: ()I 
    */ 
    JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass); 
    /* 
    * Class: testdll 
    * Method: set 
    * Signature: (I)V 
    */ 
    JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint); 
    #ifdef __cplusplus 

    #endif 
    #endif
    在具体实现的时候,我们只关心两个函数原型 
      JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass); 和 
      JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint);
    用testdll.cpp文件具体实现这两个函数: 
    #include "testdll.h" 
    int i = 0; 
    JNIEXPORT jint JNICALL Java_testdll_get (JNIEnv *, jclass) { 
    return i; 

    JNIEXPORT void JNICALL Java_testdll_set (JNIEnv *, jclass, jint j) { 
    i = j; 
    }用vc编译连接成库文件并生成DLL文件goodluck.dll 。把goodluck.dll拷贝到testdll.class的目录下,java testdll运行它,就可以观察到结果了。
      

  8.   

    swig好像不错的样子,哪位大哥能指点一下swig的使用?