c++ - GetProcAddress 与所有加载的库

标签 c++ c winapi dll

使用 dlopen,您可以提供 NULL 作为库名称,并获得一个句柄,允许您在 任何 加载的库中找到一个符号库:

If filename is a NULL pointer, then the returned handle is for the main program. When given to dlsym(), this handle causes a search for a symbol in the main program, followed by all shared libraries loaded at program startup, and then all shared libraries loaded by dlopen() with the flag RTLD_GLOBAL.

你能用 GetProcAddress 做同样的事情吗?我想搜索是否存在 Windows API,但在 Windows 8 中加载了不同的库。

我通过查看 COFF header 知道加载了哪些库,我想我可以循环遍历那里的句柄...

这是我目前使用的代码:

.hpp

#include <string>
#include <stdexcept>

/**
 * @~english
 * Looks up a Windows API function. Make sure you set @c _WIN32_WINNT so that the definition is available at compile
 * time.
 * @par Example
 * @code
 * # undef _WIN32_WINNT
 * # define _WIN32_WINNT 0x600
 * # include <system/inc/nt/windows.h>
 * static const auto initialize_srw_lock_ptr = FunctionPtrLookup(InitializeSRWLock, "kernel32");
 * @endcode
 * @param function the function definition to lookup
 * @retval nullptr the function did not exist on this version of Windows
 * @returns a function pointer to invoke
 */
#define FunctionPtrLookup(function, library) \
  FunctionLookup<decltype(function)>(#function, library)

/**
 * @~english
 * The return type of FunctionLookup
 */
typedef void(*FunctionLookupPtr)();

/**
 * @~english
 * Looks up a Windows API function. 
 * @param name the name of the function to find in the library
 * @retval nullptr the function did not exist on this version of Windows
 * @returns a function pointer to invoke
 * @see FunctionPtrLookup
 */
FunctionLookupPtr FunctionLookup(const std::string& name, const std::string& library);

/// @copydoc FunctionLookup
template<typename Signature>
const Signature * FunctionLookup(const std::string& name, const std::string& library) {
  return reinterpret_cast<const Signature*>(FunctionLookup(name, library));
}

.cpp

FunctionLookupPtr FunctionLookup(const std::string& name, const std::string& library) {
  const auto wide_library = Utf8ToWide(library);
  const auto lib = LoadLibraryW(wide_library.c_str());
  if (!lib) {
    return nullptr;
  }
  return reinterpret_cast<FunctionLookupPtr>(GetProcAddress(lib, name.c_str()));
}

理想情况下,我想删除 library 变量。

最佳答案

您可以使用 EnumProcessModules要枚举当前进程的所有加载模块,请使用此处的示例:http://msdn.microsoft.com/en-us/library/ms682621%28v=vs.85%29.aspx ,如果您使用 GetCurrentProcessId() 调用 PrintModules,它将枚举当前进程的所有 HMODULE 句柄(值在 hMods[i] 中)。您可以将它们与 GetProcAddress 一起使用以查找您的函数。

您必须意识到,可以在不同的 dll-s 中找到相同命名的函数,大多数情况下您知道 WinAPI 函数的 dll 名称。

关于c++ - GetProcAddress 与所有加载的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437007/

相关文章:

c++ - 如何实现一个简单的事件队列?

C++ 和 Python - 检查 PyObject 的类型失败

c++ - 在 VC++ 中使用 GetOpenFileName() API 打开文件夹而不是文件

c++ - 如何在 Windows 中立即刷新文件夹图标

c++ - GetClipRgn 的正确用法?

c++ - QML ListView 使用 QList<QObject*> 作为模型

c - malloc.c :3074 error?

c - mount() 上的自动检测文件系统

c - 替换字符串中的单个单词

python - Windows 7/Vista 进程管理 - 如何在长时间空闲后启动外部程序?