c++ - GetProcAddress 失败

标签 c++ winapi

<分区>

我在动态库中有一个函数,如下所示:

namespace Dll {
    int MyDll::getQ() {
        srand(time(0));
        int q = rand();
        while (!isPrime(q) || q < 100) {
            q = rand();
        }
        return q;
    }
}

.h 文件中的函数 getQ():

#ifdef _EXPORT
#define DLL_EXPORT __declspec(dllexport) 
#else
#define DLL_EXPORT __declspec(dllimport) 
#endif

namespace Dll
{
    class MyDll
    {
    public:
        static DLL_EXPORT int __stdcall getQ();
    }
}

最后 LoadLibrary 来自另一个 consoleApp 的和平代码:

typedef int(__stdcall *CUSTOM_FUNCTION)();
int main()
{

    HINSTANCE hinstance;
    CUSTOM_FUNCTION proccAddress;
    BOOL freeLibrarySuccess;
    BOOL proccAddressSuccess = FALSE;
    int result;

    hinstance = LoadLibrary(TEXT("Dll.dll"));
    if (hinstance != NULL)
    {
        proccAddress = (CUSTOM_FUNCTION)GetProcAddress(hinstance, "getQ");
        if (proccAddress != NULL)
        {
            proccAddressSuccess = TRUE;
            result = (*proccAddress)();
            printf("function called\n");
            printf("%d", result);
        }
        freeLibrarySuccess = FreeLibrary(hinstance);
    }

    if (!hinstance)
        printf("Unable to call the dll\n");

    if (!proccAddressSuccess)
        printf("Unable to call the function\n");
}

所以我多次尝试修复此问题,但总是出现“无法调用该函数”。代码连接到库,因此问题出在函数附近。 如果有人指出我的错误,我将不胜感激。

最佳答案

您缺少一个 Extern "C" .

如果不这样做,名称将被 C++ 破坏,您无法仅使用 getQ 名称找到它们。此外,这样做也不可靠,因为名称修改可能会改变。

另一个主题在这里:_stdcall vs _cdecl

关于c++ - GetProcAddress 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49599467/

相关文章:

python - 是否可以通过Python从系统托盘显示气球提示?

c++ - 运行命令行

GetWindowPlacement 处的 Perl Win32::API 缓冲区溢出

C++ 从另一个类调用( vector )指针返回空大小

c++ - 无法检查 VS Code 中的 C++ STL 内容

c++ - 二叉树搜索不返回任何结果 (C++)

python - win32api 与 Python

c++ - 使用 C++11 编写 Win32 应用程序

c++ - 列对齐问题

c++ - 重用 auto 类型的变量