![](/img/trans.png)
[英]GetProcAddress() returning null for my Hello World function
[英]Calling a function in a .dll with GetProcAddress
如何成功MYPROC
,它是指向 function 的指针: typedef void(*MYPROC)(LPCWSTR);
到(MYPROC)GetProcAddress(getdll, "myPuts");
?
考虑到GetProcAddress()
返回FARPROC
,这是一个不带参数的 function 指针,而MYPROC
带一个参数,而FARPROC
不带参数,如何转换成功?
typedef void(*MYPROC)(LPCWSTR); //you must set a function pointer to call the function in the .dll
int main(void)
{
HINSTANCE getdll;
MYPROC getprocadd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
getdll = LoadLibrary(TEXT("myPuts.dll")); // Get a handle to the DLL module.
if (getdll == NULL) {
exit(2);
}
if (getdll != NULL) // If the handle is valid, try to get the function address.
{
getprocadd = (MYPROC)GetProcAddress(getdll, "myPuts"); //GetProcAddress returns FARPROC (a function pointer for a function that takes no parameters: (FAR WINAPI *FARPROC)())
if (NULL != getprocadd) // If the function address is valid, call the function.
{
fRunTimeLinkSuccess = TRUE;
(getprocadd)(L"Message from the .dll file's function: myPuts\n");
}
fFreeResult = FreeLibrary(getdll); // Free the DLL module.
}
// If unable to call the DLL function, use an alternative.
if (!fRunTimeLinkSuccess)
printf("Message printed from executable: printf\n");
return 0;
}
演员如何成功?
因为 C 语言标准允许将 function 指针强制转换为另一个 function 指针类型。 GetProcAddress()
只返回一个指向 function 的原始指针,重要的是您要转换的类型必须与 Z5884E40D596370BE5406F2711AD9 中的实际 function 相匹配。 如果没有,当您通过强制转换的指针调用 function 时,您最终将调用未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.