跳至主要内容

24.动态链接库

动态链接库

  • 动态链接库是微软公司在微软Windows操作系统中,实现共享函数库的一种方式。
  • 这些库函数的扩展名是”.dll”、”.ocx”。
1
2
3
4
5
6
#pragma once

extern "C" _declspec(dllexport) int _stdcall Plus(int x, int y);
extern "C" _declspec(dllexport) int _stdcall Sub(int x, int y);


1
2
3
4
5
6
7
8
9
10
11
12
// pch.cpp: 与预编译标头对应的源文件

#include "pch.h"

// 当使用预编译的头时,需要使用此源文件,编译才能成功。

int _stdcall Plus(int x, int y) {
return x + y;
}
int _stdcall Sub(int x, int y) {
return x - y;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <libloaderapi.h>
#include <minwindef.h>
#include <stdio.h>
#include <windows.h>

//定义函数指针
typedef int (__stdcall *lpPlus)(int,int) ;
typedef int (__stdcall *lpSub)(int,int) ;
//声明函数指针变量
lpPlus myPlus;
lpSub mySub;



int main(int argc, char *argv[]) {
HINSTANCE hMoudle = LoadLibrary("Dll1.dll");

myPlus = (lpPlus)GetProcAddress(hMoudle,"Plus");
mySub = (lpSub)GetProcAddress(hMoudle, "Sub");

int r = myPlus(1,2);
printf("%d\n",r);
r = mySub(5,2);
printf("%d\n",r);
FreeLibrary(hMoudle);

return 0;
}

关于本文

由 GuQing 撰写,采用 CC BY-NC 4.0 许可协议。