C++ 在运行时链接期间,如何从DLL调用函数?
我不太了解DLL,所以我构建了一个简单的示例,希望能得到一些帮助。我这里有一个简单的dllC++ 在运行时链接期间,如何从DLL调用函数?,c++,dll,runtime,C++,Dll,Runtime,我不太了解DLL,所以我构建了一个简单的示例,希望能得到一些帮助。我这里有一个简单的dll // HelloDLL.cpp #include "stdafx.h" int __declspec(dllexport) Hello(int x, int y); int Hello(int x, int y) { return (x + y); } 运行LoadLibrary()后,如何在单独的程序中调用Hello(intx,inty)函数?这是一个粗略的布局,我已
// HelloDLL.cpp
#include "stdafx.h"
int __declspec(dllexport) Hello(int x, int y);
int Hello(int x, int y)
{
return (x + y);
}
运行LoadLibrary()
后,如何在单独的程序中调用Hello(intx,inty)
函数?这是一个粗略的布局,我已经到目前为止,但我不知道我有什么是正确的,如果是,如何继续
// UsingHelloDLL.cpp
#include "stdafx.h"
#include <windows.h>
int main(void)
{
HINSTANCE hinstLib;
// Get the dll
hinstLib = LoadLibrary(TEXT("HelloDLL.dll"));
// If we got the dll, then get the function
if (hinstLib != NULL)
{
//
// code to handle function call goes here.
//
// Free the dll when we're done
FreeLibrary(hinstLib);
}
// else print a message saying we weren't able to get the dll
printf("Could not load HelloDLL.dll\n");
return 0;
}
//使用hellodll.cpp
#包括“stdafx.h”
#包括
内部主(空)
{
HINSTANCE hinstLib;
//获取dll
hinstLib=LoadLibrary(文本(“HelloDLL.dll”);
//如果我们得到dll,那么就得到函数
if(hinstLib!=NULL)
{
//
//处理函数调用的代码在这里。
//
//完成后释放dll
免费图书馆(hinstLib);
}
//否则打印一条消息,说我们无法获取dll
printf(“无法加载HelloDLL.dll\n”);
返回0;
}
有人能帮我处理函数调用吗?在将来使用DLL时,我应该注意哪些特殊情况?加载库后,您需要找到函数指针。Microsoft提供的函数是GetProcAddress。不幸的是,您必须了解函数原型。如果您不知道,我们将一直使用COM/DCOM等。可能超出您的范围
FARPROC WINAPI GetProcAddress( _In_ HMODULE hModule, _In_ LPCSTR lpProcName );
在你的例子中,你通常是这样做的:
typedef int (*THelloFunc)(int,int); //This define the function prototype
if (hinstLib != NULL)
{
//
// code to handle function call goes here.
//
THelloFunc f = (THelloFunc)GetProcAddress(hinstLib ,"Hello");
if (f != NULL )
f(1, 2);
// Free the dll when we're done
FreeLibrary(hinstLib);
}
GetProcAddress();记录在。非常感谢您的回复。这是否意味着我必须为我要使用的dll中的每个函数定义一个函数原型?是的。您必须了解功能原型。然而,这实际上不是一个问题。因为调用进程和dll将共享一个公共头文件。在那里可以方便地定义它。谢谢你的积极评价。