6

I want to create a dll that unload it self in case of some condifiton, meaning

BOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
if (ul_reason_for_call==DLL_PROCESS_ATTACH)
if (!CheckSomething()) //check if a file doesnt exists for example
FreeLibrary(hModule);

}

I tried it, but i couldnt get it to work. if there is any walk around alternative solution. please tell me, I dont want the process which attached the dll to unload it, I want it to unload it self

CnativeFreak
  • 712
  • 12
  • 27
  • 1
    Avoid doing this, the client code gets a very hard to diagnose error that is no way related to the true reason the DLL can't work. You can always call CheckSomething() in whatever exported function that the client code might want to use next. – Hans Passant Dec 27 '11 at 16:45
  • @HansPassant Thanks for your reply, but in my case I cant control the client, and I need to do it this dirty way which not good practice at all ..any way I will return false in case I dont want it to be loaded .. – CnativeFreak Dec 27 '11 at 16:49

2 Answers2

17

You can't unload the DLL, it hasn't been loaded yet. That's what the BOOL return is for. If you don't want to load the DLL, then return FALSE.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Lol!, thanks alot, I didnt know that if i returned False the LoadLibrary Will freeIt. I will accept your answer after 11 min (I cant now) thanks alot again :) – CnativeFreak Dec 27 '11 at 16:41
0

If you call FreeLibrary in dll main function, you have to see crash message. Because, FreeLibrary function call is succeed. But FreeLibrary return address is freed memory. So, process causes crash!(Access violation).

If you want to see "Dll Self Unloading" source code : Dll Self Unloading

Ezbeat
  • 41
  • 3