---
title: "共享内存操作类(C#源码)"
author: "mmdev"
date: "2007-07-30T21:55:00Z"
tags: []
slug: "c"
draft: false
lastmod: "2012-08-04T21:35:29Z"
id: 1620968
url: "https://mmdev.iteye.com/blog/1620968"
---

VC++的共享内存操作代码实现起来相对比较容易，但是用C#语言来实现，就有一定难度，由于工作需要，把以前VC开发的共享内存代码要用C#实现，别说，还费了不少周折，毕竟C#操作API函数和地址指针不是那么直接，还好，总算完成了，效果还不错。

![](http://p.blog.csdn.net/images/p_blog_csdn_net/yefanqiu/Mem07073001.jpg)

共享内存操作类：

usingSystem;  
usingSystem.Collections.Generic;  
usingSystem.Text;  
usingSystem.Runtime.InteropServices;

namespaceShareMemLib  
{  
publicclassShareMem  
{  
\[DllImport("user32.dll",CharSet=CharSet.Auto)]  
publicstaticexternIntPtrSendMessage(IntPtrhWnd,intMsg,intwParam,IntPtrlParam);

\[DllImport("Kernel32.dll",CharSet=CharSet.Auto)]  
publicstaticexternIntPtrCreateFileMapping(inthFile,IntPtrlpAttributes,uintflProtect,uintdwMaxSizeHi,uintdwMaxSizeLow,stringlpName);

\[DllImport("Kernel32.dll",CharSet=CharSet.Auto)]  
publicstaticexternIntPtrOpenFileMapping(intdwDesiredAccess,\[MarshalAs(UnmanagedType.Bool)]boolbInheritHandle,stringlpName);

\[DllImport("Kernel32.dll",CharSet=CharSet.Auto)]  
publicstaticexternIntPtrMapViewOfFile(IntPtrhFileMapping,uintdwDesiredAccess,uintdwFileOffsetHigh,uintdwFileOffsetLow,uintdwNumberOfBytesToMap);

\[DllImport("Kernel32.dll",CharSet=CharSet.Auto)]  
publicstaticexternboolUnmapViewOfFile(IntPtrpvBaseAddress);

\[DllImport("Kernel32.dll",CharSet=CharSet.Auto)]  
publicstaticexternboolCloseHandle(IntPtrhandle);

\[DllImport("kernel32",EntryPoint="GetLastError")]  
publicstaticexternintGetLastError();

constintERROR\_ALREADY\_EXISTS=183;

constintFILE\_MAP\_COPY=0x0001;  
constintFILE\_MAP\_WRITE=0x0002;  
constintFILE\_MAP\_READ=0x0004;  
constintFILE\_MAP\_ALL\_ACCESS=0x0002|0x0004;

constintPAGE\_READONLY=0x02;  
constintPAGE\_READWRITE=0x04;  
constintPAGE\_WRITECOPY=0x08;  
constintPAGE\_EXECUTE=0x10;  
constintPAGE\_EXECUTE\_READ=0x20;  
constintPAGE\_EXECUTE\_READWRITE=0x40;

constintSEC\_COMMIT=0x8000000;  
constintSEC\_IMAGE=0x1000000;  
constintSEC\_NOCACHE=0x10000000;  
constintSEC\_RESERVE=0x4000000;

constintINVALID\_HANDLE\_VALUE=-1;

IntPtrm\_hSharedMemoryFile=IntPtr.Zero;  
IntPtrm\_pwData=IntPtr.Zero;  
boolm\_bAlreadyExist=false;  
boolm\_bInit=false;  
longm\_MemSize=0;

publicShareMem()  
{  
}  
~ShareMem()  
{  
Close();  
}

///&lt;summary&gt;  
///初始化共享内存  
///&lt;/summary&gt;  
///&lt;paramname="strName"&gt;共享内存名称&lt;/param&gt;  
///&lt;paramname="lngSize"&gt;共享内存大小&lt;/param&gt;  
///&lt;returns&gt;&lt;/returns&gt;  
publicintInit(stringstrName,longlngSize)  
{  
if(lngSize&lt;=0||lngSize&gt;0x00800000)lngSize=0x00800000;  
m\_MemSize=lngSize;  
if(strName.Length&gt;0)  
{  
//创建内存共享体(INVALID\_HANDLE\_VALUE)  
m\_hSharedMemoryFile=CreateFileMapping(INVALID\_HANDLE\_VALUE,IntPtr.Zero,(uint)PAGE\_READWRITE,0,(uint)lngSize,strName);  
if(m\_hSharedMemoryFile==IntPtr.Zero)  
{  
m\_bAlreadyExist=false;  
m\_bInit=false;  
return2;//创建共享体失败  
}  
else  
{  
if(GetLastError()==ERROR\_ALREADY\_EXISTS)//已经创建  
{  
m\_bAlreadyExist=true;  
}  
else//新创建  
{  
m\_bAlreadyExist=false;  
}  
}  
//---------------------------------------  
//创建内存映射  
m\_pwData=MapViewOfFile(m\_hSharedMemoryFile,FILE\_MAP\_WRITE,0,0,(uint)lngSize);  
if(m\_pwData==IntPtr.Zero)  
{  
m\_bInit=false;  
CloseHandle(m\_hSharedMemoryFile);  
return3;//创建内存映射失败  
}  
else  
{  
m\_bInit=true;  
if(m\_bAlreadyExist==false)  
{  
//初始化  
}  
}  
//----------------------------------------  
}  
else  
{  
return1;//参数错误  
}

return0;//创建成功  
}  
///&lt;summary&gt;  
///关闭共享内存  
///&lt;/summary&gt;  
publicvoidClose()  
{  
if(m\_bInit)  
{  
UnmapViewOfFile(m\_pwData);  
CloseHandle(m\_hSharedMemoryFile);  
}  
}

///&lt;summary&gt;  
///读数据  
///&lt;/summary&gt;  
///&lt;paramname="bytData"&gt;数据&lt;/param&gt;  
///&lt;paramname="lngAddr"&gt;起始地址&lt;/param&gt;  
///&lt;paramname="lngSize"&gt;个数&lt;/param&gt;  
///&lt;returns&gt;&lt;/returns&gt;  
publicintRead(refbyte\[]bytData,intlngAddr,intlngSize)  
{  
if(lngAddr+lngSize&gt;m\_MemSize)return2;//超出数据区  
if(m\_bInit)  
{  
Marshal.Copy(m\_pwData,bytData,lngAddr,lngSize);  
}  
else  
{  
return1;//共享内存未初始化  
}  
return0;//读成功  
}

///&lt;summary&gt;  
///写数据  
///&lt;/summary&gt;  
///&lt;paramname="bytData"&gt;数据&lt;/param&gt;  
///&lt;paramname="lngAddr"&gt;起始地址&lt;/param&gt;  
///&lt;paramname="lngSize"&gt;个数&lt;/param&gt;  
///&lt;returns&gt;&lt;/returns&gt;  
publicintWrite(byte\[]bytData,intlngAddr,intlngSize)  
{  
if(lngAddr+lngSize&gt;m\_MemSize)return2;//超出数据区  
if(m\_bInit)  
{  
Marshal.Copy(bytData,lngAddr,m\_pwData,lngSize);  
}  
else  
{  
return1;//共享内存未初始化  
}  
return0;//写成功  
}  
}  
}

测试例程：

usingSystem;  
usingSystem.Collections.Generic;  
usingSystem.ComponentModel;  
usingSystem.Data;  
usingSystem.Drawing;  
usingSystem.Text;  
usingSystem.Windows.Forms;  
usingShareMemLib;

namespaceYFShareMem  
{  
publicpartialclassfrmShareMem:Form  
{  
ShareMemMemDB=newShareMem();  
publicfrmShareMem()  
{  
InitializeComponent();  
}

privatevoidbtnOpen\_Click(objectsender,EventArgse)  
{  
if(MemDB.Init("YFMemTest",10240)!=0)  
{  
//初始化失败  
MessageBox.Show("初始化失败");  
}  
else  
{  
btnOpen.Enabled=false;  
chkWrite.Enabled=true;  
tmrTime.Enabled=true;  
}  
}

privatevoidtmrTime\_Tick(objectsender,EventArgse)  
{  
byte\[]bytData=newbyte\[16];  
intintRet=MemDB.Read(refbytData,0,16);  
lstData.Items.Clear();  
if(intRet==0)  
{  
for(inti=0;i&lt;16;i++)  
{  
lstData.Items.Add(bytData\[i].ToString());  
}

if(chkWrite.Checked)  
{  
bytData\[0]++;  
bytData\[1]+=2;  
if(bytData\[0]&gt;200)bytData\[0]=0;  
if(bytData\[1]&gt;200)bytData\[1]=0;  
MemDB.Write(bytData,0,16);  
}  
}  
}

}  
}