正好需要用到Java調用dll里的C接口,想到自己做個簡單的例子。我們可能需要自己生成dll文件,下邊介紹一下,詳細的步驟。主要參考https://blog.csdn.net/bingjia103126/article/details/76640464
1、在本地新建一個文件夾,用於以后存放 c project
2、在Dev c++里面新建一個C語言的DLL項目,會自動生成必要的.h、.c以及其他文件。
2、如果不做任何修改,直接編譯
3、在eclipse中創建一個project, 並創建一個java程序,注意導入依賴包jna-4.4.0.jar。

import com.sun.jna.Library; import com.sun.jna.Native; public class JNAExample { public interface CLibrary extends Library { CLibrary INSTANCE = Native.loadLibrary("world", CLibrary.class); void HelloWorld(); } public static void main(String[] args) { CLibrary.INSTANCE.HelloWorld(); } }
4、將dev-c++中編譯的world.dll copy到eclipse project的bin目錄中
5、運行JNAExample,下圖為運行結果。
補充:如果想運行最簡單的直接打印在標准輸出的hello world,可以
1、修改.h和.c文件
hello.h

#ifndef _HELLO_H_ #define _HELLO_H_ #if BUILDING_DLL #define DLLIMPORT __declspec(dllexport) #else #define DLLIMPORT __declspec(dllimport) #endif DLLIMPORT void HelloWorld(); #endif
hello.c

#include "hello.h" #include <stdio.h> DLLIMPORT void HelloWorld() { printf("Hello, World! \n"); }
運行結果如下: