如何在运行时链接期间从我的 DLL 调用函数? [英] How do I call a function from my DLL during run-time linking?
问题描述
我不太了解 DLL,所以我构建了一个简单的例子,我希望得到一些帮助.我这里有一个简单的 dll.
I do not understand DLLs very well, so I've constructed a simple example that I woudl like some help with. I have a simple dll here.
// HelloDLL.cpp
#include "stdafx.h"
int __declspec(dllexport) Hello(int x, int y);
int Hello(int x, int y)
{
return (x + y);
}
一旦我运行了 LoadLibrary()
,我将如何在单独的程序中调用 Hello(int x, int y)
函数?这是迄今为止我所拥有的粗略布局,但我不确定我所拥有的是否正确,如果正确,如何进行.
How would I call the Hello(int x, int y)
function in a separate program once I've run LoadLibrary()
? Here's a rough layout of what I have so far but I'm not sure if what I have is correct, and if it is, how to proceed.
// 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;
}
谁能帮我解决函数调用的问题?为了将来使用 dll,我应该注意哪些特殊情况?
Could anyone help me out on how to handle the function call? Any special cases I should be aware of for future usage of dlls?
推荐答案
加载库后,需要找到函数指针.微软提供的函数是 GetProcAdderess.不幸的是,你必须知道函数原型.如果您不知道,我们会一直使用 COM/DCOM 等.可能超出您的范围.
After loading the library, what you need is to find the function pointer. The function Microsoft provides is GetProcAdderess. Unfortuantely, you have to know function prototype. If you don't knwo, we are going all the way to COM/DCOM, etc. Probably out of your scope.
FARPROC WINAPI GetProcAddress( _In_ HMODULE hModule, _In_ LPCSTR lpProcName );
所以在你的例子中,你通常做的事情是这样的:
So in your example, what you do nromally is like this:
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);
}
这篇关于如何在运行时链接期间从我的 DLL 调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!