【问题标题】:C++ GetProcAddress not working [duplicate]C ++ GetProcAddress不起作用[重复]
【发布时间】:2016-02-05 14:22:25
【问题描述】:

我有以下代码:

typedef int (WINAPI* fnEngineStart)();


int __stdcall EngineStart()
{
BOOL FreeResult = 0, RunTimeLinkSuccess = 0; //variables for later use
HMODULE LibraryHandle = 0; //Here the handle to API module/dll will be stored.
fnEngineStart fn = 0;

LibraryHandle = AfxLoadLibrary(L"FlowEngine.dll"); //get the handle of our API module
//so it will now be loaded.
if (LibraryHandle != NULL) //if the library loading was successfull..
{
    fn = (fnEngineStart)GetProcAddress(LibraryHandle,
        "fnEngineStart");
    if (RunTimeLinkSuccess = (fn != NULL)) //if operation was successful...
    {
        int ReturnValue = fn(); //call messageboxa function
        //from user32.dll
    }
    else
    {
        MessageBox(0, L"Error", 0, 0);
    }
    FreeResult = FreeLibrary(LibraryHandle);
    //from this process...
    return FreeResult; //routine was successful
}
return EXIT_FAILURE; //else, it failed
}

此代码适用于例如 user32.dll 和 MessageBoxA,但不适用于我自己的 dll...

int __declspec(dllexport) __stdcall fnEngineStart()
{
   MessageBox(0, L"Succes!", 0, 0);
   return 0;
}

我如何使它也适用于我自己的 dll? 提前致谢。

【问题讨论】:

  • GetProcAddress 为 GetLastError 设置一个值 ...
  • 而那个错误码将会是127。因为函数名被修饰了。可能带有 C++ 修饰,但肯定是 stdcall 修饰。要么使用 .def 文件,或者更好的是,让名称被重整并使用其重整名称导入。

标签: c++ winapi dll loadlibrary getprocaddress


【解决方案1】:

您正在处理的问题是Name Mangling。使用extern "C" 这样编译器就不会破坏名称。示例:

extern "C" int __declspec(dllexport) __stdcall fnEngineStart()
{
   MessageBox(0, L"Succes!", 0, 0);
   return 0;
}

注意:__stdcall 函数的名称装饰有一个前导下划线,后跟一个 @,然后是堆栈上传递的参数的数量(以字节为单位)。在 32 位对齐的机器上,这个数字总是 4 的倍数。 Source

如果您的编译器支持它,您可以在您的 dll 中执行此操作,并且一切都应该按照您现在的方式运行。

extern "C" int __declspec(dllexport) __stdcall fnEngineStart()
{
   #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
   MessageBox(0, L"Succes!", 0, 0);
   return 0;
}

【讨论】:

  • 不仅如此。该函数将导出为_fnEngineStart@0。您需要使用 .def 文件或切换到 cdecl 以避免这种装饰。或者只是导入具有正确名称的函数。
猜你喜欢
  • 2011-08-06
  • 1970-01-01
  • 2018-09-10
  • 2016-07-17
  • 2018-05-01
  • 1970-01-01
  • 2016-03-07
  • 2020-10-27
相关资源
最近更新 更多