当前位置:首页 > c#中不同进程内存共享
if (strName.Length > 0) {
//创建内存共享体 (INVALID_HANDLE_VALUE)
m_hSharedMemoryFile = API.CreateFileMapping(API.INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)API.PAGE_READWRITE, 0, (uint)lngSize, strName); if (m_hSharedMemoryFile == IntPtr.Zero) {
m_bAlreadyExist = false; m_bInit = false;
return MemoryResult.Failed; //创建共享体失败 } else {
if (API.GetLastError() == API.ERROR_ALREADY_EXISTS) //已经创建 {
m_bAlreadyExist = true; }
else //新创建 {
m_bAlreadyExist = false; } }
//--------------------------------------- //创建内存映射
m_pwData = API.MapViewOfFile(m_hSharedMemoryFile, API.FILE_MAP_WRITE, 0, 0, (uint)lngSize);
if (m_pwData == IntPtr.Zero) {
m_bInit = false;
API.CloseHandle(m_hSharedMemoryFile);
return MemoryResult.Failed; //创建内存映射失败 } else {
m_bInit = true;
if (m_bAlreadyExist == false) { //初始化 } }
//---------------------------------------- } else {
return MemoryResult.Failed; //参数错误 }
return MemoryResult.Success; //创建成功 }
///
if (m_bInit) {
API.UnmapViewOfFile(m_pwData); API.CloseHandle(m_hSharedMemoryFile); } }
///
public unsafe MemoryResult Read(out T obj) {
obj = default(T);
byte[] bytData = new byte[m_size];
if (m_bInit) {
Marshal.Copy(m_pwData, bytData, 0, m_size); if (m_lastData != null) {
fixed (byte* p1 = m_lastData) {
fixed (byte* p2 = bytData) {
if (API.memcmp(p1, p2, m_size) == 0) return MemoryResult.NoChange; } } }
m_lastData = bytData;
var fmt = new BinaryFormatter();
using (var ms = new MemoryStream(bytData)) { try {
obj = (T)fmt.Deserialize(ms); }
共分享92篇相关文档