1

I have DLL which connects to EXE and works there. Exe is not my program. My DLL just create VCL child form.Is the way to unload my dll from EXE after, for example, user closed my child form?

I tried to unload my own DLL by creating thread and executing FreeLibraryAndExitThread but got Access Violation.

There I'm trying to unload dll after DLL_PROCESS_ATTACH:

#include <vcl.h>
#include <windows.h>
#include <process.h>
#include <vector>

DWORD WINAPI Eject(LPVOID Param) {

    ShowMessage("EJECT");
    FreeLibraryAndExitThread(HINSTANCE(Param), 0);
    return 1;

}

int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
    switch(reason) {

        case DLL_PROCESS_ATTACH: {

            ShowMessage("ATTACH");
            CreateThread(NULL,NULL,Eject,hinst,NULL,NULL);
            break;

        }
    }


    return 1;
}

After ShowMessage("EJECT"); my App is crashing.

Is the way to unload dll from itself?

Ivan Ivanov
  • 515
  • 1
  • 5
  • 20
  • 2
    Your thread creation deadlocks [because you're performing it from the entry point of your DLL](https://stackoverflow.com/questions/45638531/deadlock-while-using-boostasiodeadline-timer-in-windows-dll). I don't know enough to answer your question, but that's the cause of the "crash" itself. – Quentin Mar 27 '18 at 08:38
  • The answer for the access violation seems to come from @Quentin it is clearly stated that you must not unload the dll during the DLL_PROCESS_ATTACH – Tommy Andersen Mar 27 '18 at 08:40
  • Yes. Never EVER do anything 'interesting' in your DLL_PROCESS_ATTACH or DETACH calls. There's many examples out there. See (https://blogs.msdn.microsoft.com/oldnewthing/20040127-00/?p=40873)[here] for example. – Mike Vine Mar 27 '18 at 08:40
  • Deadlock is not an obvious reason. It is not very clear what ShowMessage() does. Bummer if it doesn't take enough time and the main thread is still executing inside DllEntryPoint(). Standard threading race bug, not so easy to interlock. Do show us a debugger stack trace to get ahead. – Hans Passant Mar 27 '18 at 08:46
  • First chance exception at $04EB6166. Exception class $C0000005 with message 'access violation at 0x04eb6166: read of address 0x04eb6166'. Process AD.EXE (6220). – Ivan Ivanov Mar 27 '18 at 09:02

0 Answers0