JAVA調用windows下dll檔案程式碼

來源:互聯網
上載者:User

JNA(Java Native Access):建立在JNI之上的Java開源架構,SUN主導開發,用來調用C、C++代碼,尤其是底層庫檔案(windows中叫dll檔案,linux下是so【shared object】檔案)。

JNI是Java調用原生函數的唯一機制,JNA就是建立在JNI之上,JNA簡化了Java調用原生函數的過程。JNA提供了一個動態C語言編寫的轉寄站(實際上也是一個動態連結程式庫,在Linux-i386中檔案名稱是:libjnidispatch.so)可以自動實現Java與C之間的資料類型映射。從效能上會比JNI技術調用動態連結程式庫要低。

1.簡單寫個windows下的dll,檔案命名為forjava.dll,其中一個add函數,採用stdcall呼叫慣例

 代碼如下 複製代碼

main.h檔案

#ifndef __MAIN_H__
#define __MAIN_H__
 
#include <windows.h>
 
/*  To use this exported function of dll, include this header
 *  in your project.
 */
 
#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport) __stdcall
#else
    #define DLL_EXPORT __declspec(dllimport) __stdcall
#endif
 
#ifdef __cplusplus
extern "C"
{
#endif
 
int DLL_EXPORT add(int a,int b);
 
#ifdef __cplusplus
}
#endif
 
#endif // __MAIN_H__


main.cpp


#include "main.h"
 
// a sample exported function
int DLL_EXPORT add(int a ,int b)
{
    return a+b;
}
 
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            // attach to process
            // return FALSE to fail DLL load
            break;
 
        case DLL_PROCESS_DETACH:
            // detach from process
            break;
 
        case DLL_THREAD_ATTACH:
            // attach to thread
            break;
 
        case DLL_THREAD_DETACH:
            // detach from thread
            break;
    }
    return TRUE; // succesful
}

2.將jna.jar匯入eclipse工程中,java代碼如下

 代碼如下 複製代碼

//import com.sun.jna.Library; cdecl call呼叫慣例
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.win32.StdCallLibrary;
 
public class main {
 
    public interface CLibrary extends StdCallLibrary { //cdecl call呼叫慣例時為Library
        CLibrary INSTANCE = (CLibrary)Native.loadLibrary("forjava",CLibrary.class);
        public int add(int a,int b);
    }
 
    public static void main(String[] args) {
        System.out.print(CLibrary.INSTANCE.add(2,3));
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.