Click to See Complete Forum and Search --> : Calling DllMain


sunils1
June 15th, 2005, 10:02 AM
Hi,

I want to reference my Dll name from within the DLL itself. I've tried creating a DllMain function so that I can call GetModuleFileName on the HINSTANCE passed into DllMain. The problem is that I don't think that the DllMain function is getting called as if I return FALSE in the function then it still continues to load and run. I'm not sure if my code is correct since this is all quite new to me. Here is the code:

<.cpp file>
BOOL WINAPI DllMain(HINSTANCE hinstDLL,
DWORD fdwReason,
LPVOID lpReserved )
{
// call GetModuleFileName on hinstDLL ...
return TRUE;
}

extern "C" _declspec(dllexport) int dllCallfunction(int IdButton, int MsgHandle, int ToolId)
{
...
}

<.h file>
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD,LPVOID);
extern "C" _declspec(dllexport) int dllCallfunction(int IdButton, int MsgHandle, int ToolId);

Any suggestions as to what I need to do?

Sunil

kirants
June 15th, 2005, 08:36 PM
It's not clear what is the impact since you haven't posted the whole of DllMain code.

Anyways, here is some info:
1. DllMain is called when there is an attempt to load the dll either when someone calls LoadLibrary or when some component loads the dll implicitly. DllMain also gets called when threads are spawned and threads exit.
2. If you want to know the dll name, there are couple of ways.

Option 1 - When DllMain is called with DLL_PROCESS_ATTACH, store the hInstance passed in a global variable, say in g_hInstanceDll.
Next, when the exported api is called use g_hInstanceDll to call GetModuleFileName
Option 2 - When DllMain is called with DLL_PROCESS_ATTACH, have a global string variable/char array and call GetModuleFileName right here to populate the global dll name variable, say g_szDllName. In your exported API you can then use this g_szDllName directly.


Having said this, I'd highly recommend Option 1. It is heavily discouraged to call DllMain directly or call any API within DllMain which may need other dlls to be loaded.. DllMain is generally called at program startup and if you are calling into fucntions that exist in dlls that are not yet loaded, unpredictable results occur.

So , go for Option 1 !!

sunils1
June 16th, 2005, 06:02 AM
Thanks. Works well.

kirants
June 16th, 2005, 12:30 PM
U r welcome :wave: