c++getprocaddress

GetProcAddress function usage throughout classes


I am using a DLL provided by a fellow programmer that offers certain functions I want to use in my application. The below code works as long as I use the imported functions in the same .cpp file - but not throughout all separate classes:

main.h

typedef void(*SendChat)(char*);

main.cpp

SendChat _SendChat;

HINSTANCE hMain = 0;
BOOL WINAPI DllMain(HINSTANCE hInst,DWORD reason,LPVOID)
{
    if(reason == DLL_PROCESS_ATTACH)
    {
        _beginthread(WorkerThread,0,NULL);

        hMain = LoadLibraryA("calculate.dll");
        if (hMain)
            _SendChat = (SendChat)GetProcAddress(hMain, "SendChat");
    }
    if (reason == DLL_PROCESS_DETACH)
    {
        //..
    }
    return 1;
}

The _SendChat works and does what it should do when I use it within main.cpp but as soon as I use it in the following class it does not work:

client.h

#include "main.h"

client.cpp

#include "client.h"

void MyClient::Send(char* Message)
{
    _SendChat(Message);
}

It makes sense as there's no definition of _SendChat anywhere in the client.cpp except I tried looking on how to solve this but I found nearly nothing - which makes me think I am not looking right.

Any hints are welcome.


Solution

  • To fix the compile error you need to declare variable _SendChat to be visible in the file where you want to use it. In main.h after typedef void(*SendChat)(char*); you can write the following:

    extern SendChat _SendChat;