C++共享内存存取数据的问题

哇嘎啊cc 2016-09-05 06:59:24
我自己开一个共享内存,把数据以结构体的方式存入,再另外一个程序把共享内存中的程序拷贝出来。但是发现拷贝出来的是错误的?求指教!
写入

#include <iostream>
#include <Windows.h>
#include <tchar.h>
#include <stdio.h>

using namespace std;

typedef struct _accountandpid
{
unsigned int flag[10];
unsigned int allowpidlist[10];
char account[256];
}s_ACCOUNTANDPID;


int main()
{
HANDLE h_handle;
s_ACCOUNTANDPID Saccountandpid[1];
ZeroMemory(Saccountandpid[0].account, 256);
ZeroMemory(Saccountandpid[0].flag, 10*sizeof(unsigned int ));
ZeroMemory(Saccountandpid[0].allowpidlist, 10*sizeof(unsigned int));
Saccountandpid[0].flag[0] = 1;
Saccountandpid[0].allowpidlist[0] = 908;
memcpy(Saccountandpid[0].account, "1111", 4);
// h_handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE,_T("TestFileMap"));
//创建共享文件。
h_handle = CreateFileMapping( (HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,1024,_T("TestFileMap"));

//拷贝数据到共享文件里。
LPTSTR lpMapAddr = (LPTSTR)MapViewOfFile(h_handle,FILE_MAP_ALL_ACCESS,0,0,256);
//CString strTest(_T("TestFileMap"));
CopyMemory((PVOID)lpMapAddr, &Saccountandpid, sizeof(Saccountandpid));
cout << sizeof(Saccountandpid)<<endl;
//wcscpy(lpMapAddr, (LPTSTR)Saccountandpid);

//FlushViewOfFile(lpMapAddr,sizeof(_T("TestFileMap"))+1);
//UnmapViewOfFile(lpMapAddr);
//CloseHandle(h_handle);

system("pause");

return 0;
}



读出

#include <iostream>
#include <windows.h>
#include <tchar.h>


using namespace std;

HANDLE m_hMapFile;

typedef struct _accountandpid
{
unsigned int flag[10];
unsigned int allowpidlist[10];
char account[256];
}s_ACCOUNTANDPID;

int main()
{
s_ACCOUNTANDPID accountandpid[1];

m_hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, 0,_T ("TestFileMap"));
if(NULL == m_hMapFile)
{
cout<<"m_hMapFile is NULL"<<endl;
system("pause");
return 0;
}
s_ACCOUNTANDPID lpMapAddr = (s_ACCOUNTANDPID)MapViewOfFile(m_hMapFile,FILE_MAP_ALL_ACCESS,
0,0,1024);

printf("%s", lpMapAddr);
//CopyMemory(accountandpid, lpMapAddr, sizeof(lpMapAddr));


//printf("%u", accountandpid[0].account);

system("pause");
return 0;
}
...全文
1353 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
rageliu 2016-09-26
  • 打赏
  • 举报
回复
注意数据的对齐方式。 比如读进程是4byte对齐,写进程是1bute对齐,那肯定不对。 建议把结构体加上对齐代码。
oyljerry 2016-09-05
  • 打赏
  • 举报
回复
注意对其以及读取的数据处理 地址是否准确

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧