what is the use of AFX_MANAGE_STATE?

15 01 2009

description7

 

 

We are familiar with Dynamic Link Libraries (DLLs) and most of our daily application development activities are using it. If you have an exported function in DLL and you don’t use any resources from the DLL itself  then you could invoke it from an executable module and it will work fine. 🙂

But you want to launch a dialog from the DLL module and which is from it’s own resource part. What will happen if you invoke the domodal of a dialog from any of the exported function in the DLL. No doubt, the domodal will return -1. 😦

howcanidoit15

 

 

Actually what is happening here, once we try yo launch a dialog from the DLL from its own resource – but the application holds the resource handle of the main application. So we need to switch the module state for the correct handle to be used. We can do this by adding the following code to the beginning of the exported function in the DLL,

AFX_MANAGE_STATE( AfxGetStaticModuleState() );

This swaps the current module state with  the state returned from AfxGetStaticModuleState( ) until the end of the current scope. This is a macro used to protect an exported function in a DLL.

mycodesnippet5

 

 

Regular DLL exported function

extern "C"
void _declspec(dllexport) MyExportedFunction(void)
{
   AFX_MANAGE_STATE( AfxGetStaticModuleState() );
  
   CMyCustomDialog MyCustomDlg;
  
   if( -1 == MyCustomDlg.DoModal() )
   {
      AfxMessageBox("failed");
   }  
}

Main application function

typedef void (CALLBACK* LPFUNPOINT)(void);

void LoadDLLFunction()
{
   //Load your dll from the path
   HMODULE hm = LoadLibrary("D:\\SAN\\RegularDll\\Debug\\RegularDll.dll");
  
   LPFUNPOINT   lpProc;
   if(NULL != hm)
   {
      lpProc = (LPFUNPOINT)GetProcAddress(hm, _T("MyExportedFunction") );
      if(NULL != lpProc)
         lpProc();
   }
}

mynote6

 

 

That’s working fine in the Regular DLL, now if we try the same routine with the MFC Extension DLL it may lead to a link error like this,

mfcs42d.lib(dllmodul.obj) : error LNK2005: __pRawDllMain already defined in ExtensionDLL.obj

How can we remove this. Please follow the link MIcrosoft: Help and Support.

Advertisements