动态链接库
0x00-参考文章
https://blog.csdn.net/LyRics1996/article/details/120246497
0x01-创建动态链接库
下面以VS为例
在创建新项目找到动态链接库DLL
创建之后是这样的
替换成我们待会要调用的函数
之所以要在函数前面加上extern “C” __declspec(dllexport)
是因为在导出的时候可能会增加一些符号,这样的话函数的名称会被修改,待会GetProcAddress就无法调用了
0x03-调用动态链接库
首先先要加载动态链接库,使用LoadLibrary,有两种方式
1 2
| handle = LoadLibrary(L"Dll1.dll"); handle = LoadLibrary(_TEXT("D:\\new\\AD\\C语言\\Dll1\\Debug\\Dll1.dll"));
|
使用下面这种方式的话需要#include<tcahr.h>
GetProcAddress调用DLL文件中的函数
我们需要使用typedef为函数指针创建匹配类型的指针
因为函数名就是函数的地址,所以可以直接赋值和调用,下面两种都可以调用函数,震惊!C语言白学了
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include<stdio.h> #include<Windows.h> #include<string.h> #include<iostream> #include <tchar.h>
typedef int(*Lpfunc)(int a,int b); int main() { HMODULE handle; handle = LoadLibrary(L"Dll1.dll"); handle = LoadLibrary(_TEXT("Dll1.dll")); Lpfunc add = NULL; add = (Lpfunc)GetProcAddress(handle, "add"); printf("%d\n", add(3, 4)); FreeLibrary(handle); return 0; }
|
typedef声明函数指针
https://blog.csdn.net/afei__/article/details/82011613
当然我们也可以多层调用
dll文件中
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include "pch.h" #include<stdio.h> extern "C" _declspec (dllexport)void Print(int k) { printf("%d\n", k); } extern "C" _declspec (dllexport)int add(int a, char b) { int c = a + b; Print(c); return c; }
|
python调用dll-ctype
https://docs.python.org/3/library/ctypes.html