C#如何用内存映射一个结构并读写
private void CreateMapFilebuf()
{
IntPtr intptr = IntPtr.Zero;
try
{
if (!LockMapfile())
{
MessageBox.Show("无法注册用户信息请稍后重启程序!");
return;
}
hMapFile = OpenFileMapping(0x0002 | 0x0004, false, "CMB_GKE_MAPPINGFILE");
if (hMapFile == 0)
{
hMapFile = CreateFileMapping(0xFFFFFFFF, 0, PAGE_READWRITE, 0, size, "CMB_GKE_MAPPINGFILE");
if (hMapFile == 0)
{
MessageBox.Show("初始化内存失败!");
return;
}
}
intptr = MapViewOfFile(hMapFile, FILE_MAP_WRITE, 0, 0, 0);
Sequentialdata = (DATA)Marshal.PtrToStructure(intptr, typeof(DATA));
Sequentialdata.FromSys = "OS";
Sequentialdata.ClassNamePre = "CLIENT";
Sequentialdata.MsgTyp = "0;1;";
Sequentialdata.MsgNotifyTyp = 0;
Sequentialdata.AppCount = 1;
}
catch
{
}
finally
{
if (intptr != IntPtr.Zero)
{
UnmapViewOfFile(intptr);
}
UnLockMapfile();
}
}
其中 [StructLayout(LayoutKind.Sequential)]
public struct DATA
{
[MarshalAs(UnmanagedType.BStr, SizeConst = 20)]
public string FromSys;
[MarshalAs(UnmanagedType.BStr, SizeConst = 50)]
public string ClassNamePre;
[MarshalAs(UnmanagedType.BStr, SizeConst = 20)]
public string MsgTyp;
public int MsgNotifyTyp;
public int AppCount;
};是定义的结构
但是执行代码时第一次是CreateFileMapping并且映射成功 当修改了
Sequentialdata = (DATA)Marshal.PtrToStructure(intptr, typeof(DATA));
Sequentialdata.FromSys = "OS";
Sequentialdata.ClassNamePre = "CLIENT";
Sequentialdata.MsgTyp = "0;1;";
Sequentialdata.MsgNotifyTyp = 0;
Sequentialdata.AppCount = 1;
之后UnmapViewOfFile(intptr);提交
下次再读取的时候 得到的Sequentialdata还是没有修改前的 请各位看看哪有问题,谢谢