user2295277
user2295277

Reputation: 219

Functions in a DLL

I have a dll with some functions. Header exemple:

__declspec(dllexport) bool Test()

; And i have another simple application to use that function:

typedef bool(CALLBACK* LPFNDLLFUNC1)();

HINSTANCE hDLL;               // Handle to DLL
LPFNDLLFUNC1 lpfnDllFunc1;    // Function pointer
bool uReturnVal;

hDLL = LoadLibrary(L"NAME.dll");
if (hDLL != NULL)
{
    lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,"Test");
    if (!lpfnDllFunc1)
    {
        // handle the error
        FreeLibrary(hDLL);
        cout << "error";
    }
    else
    {
        // call the function
        uReturnVal = lpfnDllFunc1();
    }
}

But don't work. The function isn't found.

Upvotes: 1

Views: 1114

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400612

My psychic senses tell me that the function wasn't found because you forgot to declare it as extern "C".

Because of name mangling in C++, the actual function name that gets put into the DLL's export table is a longer, more gibberish-y string than just Test if the function has C++ linkage. If you instead declare it with C linkage, then it will be exported with the expected name and can therefore be imported more easily.

For example:

// Header file
#ifdef __cplusplus
// Declare all following functions with C linkage
extern "C"
{
#endif

__declspec(dllexport) bool Test();

#ifdef __cplusplus
}
// End C linkage
#endif

// DLL source file
extern "C"
{

__declspec(dllexport) bool Test()
{
    // Function body
    ...
}

}  // End C linkage

Upvotes: 3

Related Questions