包装loadlibrary的c++类
C++ class to wrap loadlibrary?
我认为有几个类分别围绕LoadLibrary
和GetProcAddress
, Library
和Function
将是很酷的。当我在思考这个问题时,我不确定这是否可能。我是这么想的:
Library
class:
class Library
{
HANDLE m_handle;
public:
// Handles initializing the DLL:
Library(std::string name);
// Deinitializes the DLL
~Library();
HANDLE getHandle();
bool isInitialized();
}
和Function
类:
class Function
{
public:
Function(Library& library, std::string name);
void* call(/* varg arguments? */) throw(exception);
bool isValid();
}
问题出现了,因为我必须有动态数据类型的参数和多个长度传递给真正的函数指针。我可以通过在构造函数中指定参数并使用特定的方法来解决参数的多个长度问题但是数据类型呢?编辑:我已经根据答案创建了类,供任何人在这里使用:https://github.com/ic3man5/ice--
可以实现隐式转换为函数指针。
template <typename Signature>
struct Function
{
Function(Library& library, std::string name)
{
m_func = reinterpret_cast<Signature *>(
::GetProcAddress(library.m_hModule, name.c_str()));
}
operator Signature *() { return m_func; }
private:
Signature * m_func;
};
按如下方式使用类:
Function<int (int, double)> foo(library, "foo");
int i = foo(42, 2.0);
你可以看看Qt的QPluginLoader &QLibrary .
关于调用带有任意签名的动态加载函数,您可以使用LibFFI
所有这些都是从Linux的角度来看,我不知道Windows,我不知道等效的(但两者都是Qt &LibFFI被移植到Windows)
请注意,通过指针调用任意函数可能是编译器、处理器和ABI特定的(因此libFFI包含不可移植的代码)。
相关文章:
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- Windows 链接器是否使用 LoadLibrary 解析 DLL 中未定义的符号?
- 如何将 std::filesystem::p ath 转换为 LPCSTR,以便在 LoadLibrary() 变体之一
- 为什么 LoadLibrary 失败,而 LoadLibraryA 成功加载 DLL?
- 如何链接 DLL 以供 LoadLibrary() 使用(在 Windows 上的 C++ 中)并从调用 exe 导入变
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- LoadLibrary:在发布模式下崩溃
- Java System.loadLibrary 不会在 /usr/lib/x86_64-linux-gnu/ 文件夹中查
- LoadLibrary('user32.dll') 返回 14007
- 调试通过 LoadLibrary() 加载到 Excel 中的C++ DLL
- java native loadLibrary 无法加载库 - Linux fedora25 java8
- C 中的简单现代跨平台Dlopen/LoadLibrary包装器
- 使用 LoadLibrary 返回 0,Win32Error 193
- C++单元测试项目 LoadLibrary 失败,出现"序号未找到"错误
- 我可以在 Win32 DLL 中使用 LoadLibrary 吗?
- 哪种方法更好获取静态链接DLL的模块句柄(HMODULE) - 使用GetModuleHandleEx()或LoadLibrary()?
- LoadLibrary失败带有错误4250:此操作仅在应用程序容器的上下文中有效
- winapi函数loadLibrary()导致函数在执行错误期间失败
- LOADLIBRARY(..)失败错误代码1627:error_function_failed
- LoadLibrary 永远不会在 Visual Studio 2013 c++ 项目中返回