anom1
anom1

Reputation: 113

How to dll import and export HINSTANCE from a .dll in c++?

I am trying to get the HINSTANCE of a .dll, but I get this error:

error LNK2019: unresolved external symbol "__declspec(dllimport) struct HINSTANCE__ * m_instance" (__imp_?m_instance@@3PEAUHINSTANCE__@@EA) referenced in function...

This is the code of the .dll:

#include <Windows.h>

__declspec(dllexport) HINSTANCE m_instance;

BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID)
{
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
        m_instance = (HINSTANCE)hModule;
    }

    return TRUE;
}

This is the code of the application:

__declspec(dllimport) HINSTANCE m_instance;

// use it for whatev

In summary, I need a way to get the HINSTANCE from my .dll into my .exe.

Upvotes: 0

Views: 552

Answers (2)

IInspectable
IInspectable

Reputation: 51395

The application is failing to link against the DLL's import library. By default, MSVC's linker generates an import library (LIB) when producing a DLL, that has the same base name as the DLL.

To allow the linker to resolve the symbol m_instance the application needs the DLL's import library as a linker input file. See .Lib Files as Linker Input to learn how to add linker input files in Visual Studio.

Though not strictly required, it's usually a good idea to export symbols using C linkage. While C++ linkage is largely unspecified and very toolchain-specific, C name decoration is de-facto standardized. The changes required are tiny (though, again, not required):

extern "C" __declspec(dllexport) HINSTANCE m_instance;

and

extern "C" __declspec(dllimport) HINSTANCE m_instance;

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 596176

In summary, I need a way to get the HINSTANCE from my .dll into my .exe.

But, why??? Once the .exe has loaded the .dll into its memory, the .exe already has access to the .dll's HINSTANCE, from the return value of either LoadLibrary/Ex() or GetModuleHandle(). So, there is never a need to have a .dll export its own HINSTANCE.

Upvotes: 3

Related Questions