假设有一个hello.dll文件,里面有个函数hi(),打印一句问候的字符串。

需要用Java来调用这个动态链接库文件,并调用hi()函数,如何实现呢?


一、使用codeblocks创建dynamic link library工程

wKioL1SUJhXjE0ijAAGKQqPx0Rs726.jpg

C代码如下:

  • demo.h

#ifndef DEMO_H_INCLUDED
#define DEMO_H_INCLUDED
#include <windows.h>
#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif
void DLL_EXPORT hi();
#endif // DEMO_H_INCLUDED


  • demo.c

#include <stdio.h>
#include "demo.h"
void DLL_EXPORT hi()
{
    printf("Nice to meet you\n");
}

构建hello工程以后,会在Debug和Release目录下生成hello.dll文件,

wKiom1SUJ_7Qdu_eAAAw_KNdnhk076.jpg

把这个文件复制到Java工程目录下,指定好classpath即可调用。


二、创建Java调用代码

Java代码很简单:

import com.sun.jna.Library;
import com.sun.jna.Native;
interface MyNativeLib extends Library{
    String dllName = "hello";
    MyNativeLib INSTANCE = (MyNativeLib)Native.loadLibrary(dllName, MyNativeLib.class);
    
    // 动态链接库里的函数
    void hi();
}
public class InvokeNativeDemo {
    public void greeting(){
        MyNativeLib.INSTANCE.hi();
    }
    
    public static void main(String[] args) {
        InvokeNativeDemo demo = new InvokeNativeDemo();
        demo.greeting();
    }
}

wKiom1SUJ7bQ9sP1AABzQ28ARRE607.jpg




三、如果要在C语言中调用hello.dll的hi函数,建立一个新工程Console工程test

  • main.c

#include <stdio.h>
#include <stdlib.h>
#include "demo.h"
int main()
{
    hi();
    getchar();
    return 0;
}


  • demo.h (这个头文件和hello.dll工程的头文件一样)

#ifndef DEMO_H_INCLUDED
#define DEMO_H_INCLUDED
#include <windows.h>
#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif
void DLL_EXPORT hi();
#endif // DEMO_H_INCLUDED


在build之前,需要在build option中对linker setting就行设置,指向库文件的中间文件.a文件

wKiom1SUKdai4_XWAAIEBgIsAKk341.jpg


然后将hello.dll放入相应的Debug或者Release目录

wKiom1SUKomxMwaWAAB19fZjniQ613.jpg


C调用hello.dll的执行结果也为 Nice to meet you