【C/C++】C/C++中调用dll动态链接库的方法

dexfire · 2020-4-14 · 次阅读


【C/C++】C/C++中调用dll动态链接库的方法

*.dll是Windows平台中动态链接库的后缀名,由于函数和资源复用是非常基础的设计原则,所以动态链接库无论是何种平台,何种领域的应用软件中的使用都非常广泛。

首先:创建一个dll函数库文件

文件名:test.c

#include <stdio.h>

int add(int a, int b){
    return a+b;
}

void hello(void){
    printf("Hello, from test.dll!");
}

编译

>>> gcc -c test.c
>>> gcc -shared -o test.dll test.o

这样就输出了一个test.dll文件。

然后,在另一个exe文件中调用test.dll

文件名:dll_caller.cpp

#include <stdio.h>
//#include <mingw32.h>
#include <Windows.h>

typedef void (*hello)(void);
typedef int (*add)(int a, int b);

// int add(int, int);
// void hello();

int main(){
    HMODULE  hdll = LoadLibrary("test.dll");
    if (hdll != NULL){
        hello hello1 = (hello) GetProcAddress(hdll, "hello");
        add add1 = (add) GetProcAddress(hdll, "add");
        printf("调用DLL结果:\n\t");
        hello1();
        printf("\n\t3+4=%d", add1(3, 4));
    } else {
        printf("error when loadding library!");
    }
}

编译

>>> clang -c dll_caller.cpp
>>> clang -o dll_caller.exe dll_caller.o

这样就生成了可执行文件 dll_caller.exe ,直接运行,可以看到结果:

the files generated by gcc

$ ./dll_caller.exe
调用DLL结果:

   3+4=7Hello, from test.dll!

途中遇到的问题

  • 使用gcc引用windows.h时,发现会报错,未找到一大堆变量,应该是使用的是mingw32的target的缘故,改用clang编译,问题解决。
  • 这里对函数签名和返回值的定义,需要记忆一下,这是一种基本模式。