JAVA技巧:多語言調(diào)用之Java調(diào)用C/C++

字號:

Java 調(diào)用 C/C++
    1.創(chuàng)建一個類com.test.TestCall
    內(nèi)容如下
    package com.test;
    public class TestCall {
    public native String getResponse(String request);
    }
    2.編譯得到TestCall.class文件
    命令javah com.test.TestCall(如果不好使,前面執(zhí)行一句set classpath=.)
    得到com_test_TestCall.h文件,內(nèi)容如下
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include
    /* Header for class com_test_TestCall */
    #ifndef _Included_com_test_TestCall
    #define _Included_com_test_TestCall
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
    * Class: com_test_TestCall
    * Method: getResponse
    * Signature: (Ljava/lang/String;)Ljava/lang/String;
    */
    JNIEXPORT jstring JNICALL Java_com_test_TestCall_getResponse
    (JNIEnv *, jobject, jstring);
    #ifdef __cplusplus
    }
    #endif
    #endif
    3.新建C/C++工程,引入com_test_TestCall.h頭文件
    TestCall.cpp
    #include "com_test_TestCall.h"
    JNIEXPORT jstring JNICALL Java_com_test_TestCall_getResponse
    (JNIEnv *pEnv, jobject obj, jstring jstr)
    {
    jstring response = pEnv->NewStringUTF("call C:");
    jboolean isCpoy;
    const jchar *request = pEnv->GetStringChars(jstr,&isCpoy) ;
    //todo
    pEnv->ReleaseStringChars(jstr,request);
    return response;
    }
    編譯成TestCall.dll
    4.將TestCall.dll放到eclipse工程下(或者運行參數(shù)java -Djava.library.path=“dll目錄”)
    完整TestCall.java
    package com.test;
    public class TestCall {
    static
    {
    //dll名字
    System.loadLibrary("TestCall");
    }
    public native String getResponse(String request);
    public static void main(String[] args)
    {
    TestCall call = new TestCall();
    String message = call.getResponse("hello");
    javax.swing.JOptionPane.showMessageDialog(null, message);
    }
    }
    5.運行java,彈出對話框就算成功了。
    當然現(xiàn)在有Java Native Access這個開源項目,方便了我們的調(diào)用。
    JNA里面不需要按照com_test_XX這種格式定義頭文件,只要定義一個方法接口,支持指針,非常好用。