Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does AFX_MANAGE_STATE(AfxGetStaticModuleState()) do exactly

Tags:

c++

mfc

I have used a lot of modal dialogs and they worked fine without the use of AFX_MANAGE_STATE, but recently I was working on a different project in which the resource dlls are different from the launching dll. I surfed the web and found out the above line and when I inserted it before launching the dialog, it worked. I guess that maybe since we have different dlls, we need to load the state of the main dll in order to launch the dialog, but I am not sure. I have not been able to find a good explanation anywhere on the internet. Could anyone please explain in simple terms what AFX_MANAGE_STATE does and why I suddenly had to use it.

Thanks.

like image 747
dev ray Avatar asked Jan 30 '12 09:01

dev ray


2 Answers

Every .exe and .dll has an internal resource handle, pointing to your dialogs and other resources. If you call a function in your DLL, the current resource handle is pointing to the resources in the .exe, which is wrong and needs to be changed to the resources of the DLL.

This is what AFX_MANAGE_STATE does.

like image 160
dwo Avatar answered Nov 16 '22 02:11

dwo


AFX_MANAGE_STATE is a macro which calls resource function so that resource would be looked up only in this DLL, and not the EXE/DLL from which particular function is called. This macro also causes AFX_MAINTAIN_STATE class to be put on stack. This class would, on exit of function, reset the resource lookup, so that EXE/DLL that called this exported function gets it resource searching back.

In C++ terms:

// Some exported function that launches GUI or uses other resources
int GetSomething()
{
   AFX_MANAGE_STATE();
  ...
}

Would be something like (not exactly):

int GetSomething()
{
       SetResourceSearchingToThisDLL();

       AFX_MAINTAIN_STATE state_RAII; 

       //Use resource

       // Compiler will put destroctor call for state_RAII object here
       // which will mean AFX_MAINTAIN_STATE::~AFX_MAINTAIN_STATE()
       // And that would call something like:
       ResetResourceSearching();
}

Usage of this macro, within same DLL call stack wont hurt anyone, since Resource-Searching has some usage-counter, which will revert to caller (DLL/EXE resource) only if it reaches 0.

It is important to note that, not every MFC DLL has to use this macro. It is only if DLL is loaded by non-MFC client, may be by a C client, a C++ console based application, .NET client etc (yes, may be MFC Windows application client also).

If your EXE and DLL are made in MFC, using same MFC/Compiler/linker version and has one CWinApp object, you need not to use this macro.

like image 17
Ajay Avatar answered Nov 16 '22 03:11

Ajay