Search code examples
c++dllvisual-studio-2017windows-xpstatic-variables

Simple DLL created in Visual Studio 2017 doesn't load in XP


Platform Toolset - Visual Studio 2017 - Windows XP (v141_xp)

Runtime library - Multi-threaded (no CRT dependencies)

DLL loads fine on Vista+, but fails on XP SP2 (x86) with error code ERROR_NOACCESS (Invalid access to memory location)

dll code:

#include <windows.h>
#include <string>

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        {
            static std::string test;
            break;
        }
    }

    return TRUE;
}

exe code:

#include <Windows.h>
#include <tchar.h>

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
    HMODULE hModule = LoadLibrary(L"dll.dll");

    if (hModule)
        MessageBoxA(0, "It works", "Info", MB_ICONINFORMATION);
    else
    {
        char buff[10];
        _itoa_s(GetLastError(), buff, 10, 10);

        MessageBoxA(0, buff, "GetLastError()=", MB_ICONEXCLAMATION);
    }

    return 0;
}

Same problem for Visual Studio 2015. Though it works fine when compiled in Visual Studio 2013.

Download VS017 solution


Solution

  • Windows XP has this restriction. When you load a DLL with LoadLibrary, that particular DLL cannot have a static data inside the DLL. It cannot be solved. You need to find another approach.