CSharedMemory, A Small Class to Share Data Via File Mapping | CodeGuru

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: […]

Written By
CodeGuru Staff
CodeGuru Staff
Oct 18, 2001
1 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

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

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.