CSharedMemory, A Small Class to Share Data Via File Mapping

Environment: VC6 SP4, NT4 SP6,W98 SE, W2000 SP1

With this class, only a few lines are needed to communicate with other processes. I use it from storing HWNDs,status flags up to memory resistent fifo queues.

At least one process should keep the memory open. The CSharedMemory as a Member of CMyClass

class CMyClass
{
public:
CSharedMemory m_sm;
MyDataSruct* m_pData;

Initialisation in the constructor of CMyClass with a system wide unique name for this memory block.

CMyClass::CMyClass(..)
{
m_sm.Init(“MyUniqueMemoryName”,sizeof(MyDataSruct));
m_pMyData = (MyDataSruct*)m_sm.GetData();
//maybe if it is the first process
if( ! m_sm.AlreadyExist())
ZeroMemory(m_pMyData,sizeof(MyDataSruct));

Using synchronisation:

{
CSharedMemory::Locker lock(m_sm);
DoSomethingWith(m_pData);
}
//or wait only 100 milliseconds
if( m_sm.Lock( 100 ) )
{
DoSomethingWith(m_pData);
m_sm.Unlock();
}

And because I’m lazy, somtimes I use only this:


CSharedMemory sm(“MyUniqueMemoryName”,sizeof(MyDataSruct));
((MyDataSruct*)sm.GetData())->m_nMyMember = 123;

Downloads

Download demo project – 13 Kb

The latest versions may be found at:
www.schikos.de

More by Author

Must Read