[toc]
使用C语言在windows中动态调用自己写的动态链接库 1.使用C语言在VistualStudio2022中创建动态链接库项目
新建项目->windows桌面->动态链接库(DLL)->项目名称dll1
属性->c/c++->代码生成->运行库设置为多线程调试DLL(/MTd)
选择Solution Explorer->Property->c/c++->Procompiled Headers->选择Not Using Precompiled Headers
新建文件myfunc.h,与myfunc.c
myfunc.h
1 2 3 4 #pragma once __declspec(dllexport) int add (int numberA, int numberB) ;
myfunc.c
1 2 3 4 5 6 7 8 #include "pch.h" #include "myfunc.h" int add (int numberA, int numberB) { return numberA + numberB; }
dllmain.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <windows.h> BOOL APIENTRY DllMain ( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break ; } return TRUE; }
4.编译生成
2.新建一个c语言项目调用刚刚生成的DLL文件里的函数
编写代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <stdio.h> #include <windows.h> typedef int (*addition) (int numberA, int numberB) ;int main () { HMODULE hDll = LoadLibraryA ("DLL1.dll" ); addition function = (addition)GetProcAddress (hDll, "add" ); int result = function (1 , 2 ); printf ("%d\r\n" , result); system ("pause" ); return 0 ; }
将dll文件放入项目中
编译运行程序
C语言程序调用动态链接库中的全局变量 1.编写动态链接库代码 添加空项目
1右键项目->添加新建项->修改名称MyDll
2在属性->常规->配置类型中改为动态库.Dll
3.添加源文件DllMain.cpp
4.写入口函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <windows.h> int _declspec(dllexport) varlabel = 10 ;BOOL APIENTRY DLLMain (HMODULE hModule,DWORD call_Reason,LPCVOID lpReserved) { switch (call_Reason) { case DLL_PROCESS_ATTACH: break ; case DLL_THREAD_ATTACH: break ; case DLL_THREAD_DETACH: break ; case DLL_PROCESS_DETACH: break ; } return TRUE; }
5.编译成dll文件并复制到调用dll的程序文件夹里面
2.编写C语言程序调用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <stdio.h> #include <windows.h> int main () { HMODULE DLL = LoadLibraryA("DLL1.dll" ); if (!DLL) { printf ("加载DLL失败\n" ); } int varlabel = *(int *)GetProcAddress(DLL, "varlabel" ); printf ("var is %d\n" , varlabel); Sleep(200000 ); return 0 ; }
动态加载User32.dll中的MessageBoxA函数 完整代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <windows.h> #include <stdio.h> int main () { HMODULE hUser32 = LoadLibraryA ("User32.dll" ); typedef int (WINAPI* MessageBoxA_t) (HWND, LPCSTR, LPCSTR, UINT) ; MessageBoxA_t pMessageBoxA = (MessageBoxA_t)GetProcAddress (hUser32, "MessageBoxA" ); pMessageBoxA (NULL , "Hello, World!" , "My Message Box" , MB_OK); FreeLibrary (hUser32); return 0 ; }