使用 GetProcAddress Function 时,有以下几点需要特别留意:
4. 最好用函数名,而不是 ordinal 值调用 GetProcAddress,以避免不同版本 Dll 中某些函数不存在的情况。
注:确认 Dll 的导出函数名,可以用 DUMPBIN /EXPORTS dll_file_name.dll 命令,然后查看 name 列。
- // The myPuts function writes a null-terminated string to
- // the standard output device.
- // The export mechanism used here is the __declspec(export)
- // method supported by Microsoft Visual Studio, but any
- // other export method supported by your development
- // environment may be substituted.
- #include <windows.h>
- #define EOF (-1)
- #ifdef __cplusplus // If used by C++ code,
- extern "C" { // we need to export the C interface
- #endif
- __declspec(dllexport) int __cdecl myPuts(LPTSTR lpszMsg) // __cdecl | __stdcall | __fastcall
- {
- DWORD cchWritten;
- HANDLE hStdout;
- BOOL fRet;
- // Get a handle to the standard output device.
- hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
- if (INVALID_HANDLE_VALUE == hStdout)
- return EOF;
- // Write a null-terminated string to the standard output device.
- while (*lpszMsg != '\0')
- {
- fRet = WriteFile(hStdout, lpszMsg, 1, &cchWritten, NULL);
- if( (FALSE == fRet) || (1 != cchWritten) )
- return EOF;
- lpszMsg++;
- }
- return 1;
- }
- #ifdef __cplusplus
- }
- #endif
[cpp] view plain copy
- // A simple program that uses LoadLibrary and
- // GetProcAddress to access myPuts from Myputs.dll.
- #include <stdio.h>
- #include <windows.h>
- typedef int (__cdecl *MYPROC)(LPTSTR); // __cdecl | __stdcall | __fastcall
- VOID main(VOID)
- {
- HINSTANCE hinstLib;
- MYPROC ProcAdd;
- BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
- // Get a handle to the DLL module.
- hinstLib = LoadLibrary(TEXT("bin\\Myputs")); // 虽然 MSDN Library 说这里如果
- // 指定了路径,要用 backslashes (\),
- // 不要用 forward slashes (/),但
- // 其实用二者都可以。
- // 注:如果用 \,要用 \\。
- // If the handle is valid, try to get the function address.
- if (hinstLib != NULL)
- {
- ProcAdd = (MYPROC)GetProcAddress(hinstLib, "myPuts"); // __cdecl : myPuts
- // __stdcall : _myPuts@4
- // __fastcall: @myPuts@4
- // If the function address is valid, call the function.
- if (NULL != ProcAdd)
- {
- fRunTimeLinkSuccess = TRUE;
- (ProcAdd) (TEXT("Message via DLL function\n"));
- }
- // Free the DLL module.
- fFreeResult = FreeLibrary(hinstLib);
- }
- // If unable to call the DLL function, use an alternative.
- if (! fRunTimeLinkSuccess)
- printf("Message via alternative method\n");
- }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架