Hi ppl!!
My problem is simple. I'm supposed to implement a counter that counts how applications/instances of applications are using my DLL.
I need the counter to be a shared variable. I am new to C++ and I tried out a few things without success.
Note:I'm using VC++ 2010 and my applications load the DLL with LoadLibrary() function.
Okay first I tried the #pragma data_seg directive. This is my DLL .cpp code.
__________________________________________________________________
#pragma data_seg(".myseg")
long Counter2=0;
#pragma data_seg()
#pragma comment(linker, "/section:.myseg,RWS")
EXPORT int Add(int a, int b)
{
return a+b;
}
____________________________________________________________
the problem with this?
each time an application uses the DLL, Counter2 is initialized to 0. and so it never gets incremented!!!
So anyways, I tried this second implementation using memory mapped files, but ran into a problem again.
1. I used the CreateFileMapping() and MapViewOfFile()...but apparently you can only write WCHAR strings into MMF(mem mapped file)s. How do I put my integer counter in there?
2. How do I initialize the MMF? How will my DLL know if it's being used by the first application or the second or the third?
I am pasting my stupid DLL .cpp code that doesnt work, just in case that helps.
Okay, but how do I initialize the file. If I write the initialization code in the .cpp file of my DLL, it will get initialized every time the DLL is used.
I don't know if I really understand what you mean.
Note this:
MSDN wrote:
Prefixing the file mapping object names with "Global\" allows processes to communicate with each other even if they are in different terminal server sessions.
CreateFileMapping() must fail if a process has already done it
@coder777: Just 1 thing. I'll make this question as clear as possible. Suppose I have 2 apps loading my DLL- App1 and App2.
Suppose App1 is the first app that loads the Dll, so when it does tht, it has to initialize the memory mapped file.(with 0). How do I write a code such that it is initialized to 0 only when App1 loads it, and not everytime any app loads it. Basically, I want to make sure that if I write a code for initializing, it does not initialize everytime the DLL is loaded, but only when the first app loads it.
I hope I've made my question clear.
if you were able to CreateFileMapping (the result hMapFile != NULL) you know that you are the first and you need to initialize the memory.
There's a problem when two programs are starting at the same time. The second program may OpenFileMapping before you initialized it. To make it fool proof you need named mutex