您好,我想使用 microsoft 的文件映射将 P1 进程中的类中的对象共享到 P2.exe 进程:https ://msdn.microsoft.com/fr-fr/library/windows/desktop/aa366537(v= vs.85).aspx。
P1 写入数据,P2 读取它们。我想共享所有数据,但它不起作用。
P1:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <iostream>
#include <string>
using namespace std;
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
class Object
{
public:
string nameWindow;
string nameLogFile;
HWND hwndWindow;
HANDLE histFile;
WIN32_FIND_DATA dataFile;
};// members to read
int _tmain()
{
Object add;
HANDLE hMapFile;
add.nameLogFile= "Logfil";
add.nameWindow = "Windowstest";
Table *bufData;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
sizeof(Table), // maximum object size (low-order DWORD)
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
return false;
}
bufData = (Object*)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(Table));
if (bufData == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return false;
}
CopyMemory((PVOID)bufData, &add, sizeof(Table));
cout << "Mise en memoire " << endl;
_getch();
UnmapViewOfFile(bufData);
CloseHandle(hMapFile);
}
P2:
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <string>
using namespace std;
#pragma comment(lib, "user32.lib")
class Object
{
public:
string nameWindow;
string nameLogFile;
HWND hwndWindow;
HANDLE histFile;
WIN32_FIND_DATA dataFile;
};// members to write
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");
int _tmain()
{
HANDLE hMapFile;
LPCTSTR pBuf;
Table *bufData=new Table;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object (%d).\n"),
GetLastError());
return 1;
}
bufData = (Object*)MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
sizeof(Object));
if (bufData == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
cout << "DATA" << endl;
cout << "Log:" << bufData->nameLogFile<<endl;
cout << "Window:" << bufData->nameWindow << endl;
UnmapViewOfFile(bufData);
CloseHandle(hMapFile);
system("pause");
return 0;
}
所以我只尝试使用 2 个字符串进行测试:add.nameLogFile= "Logfil" 和 add.nameWindow = "Windowstest"; 两者的大小。P2 可以很好地读取两个字符串。
但是当我有一个字符(add.nameWindow = "Windowstest+" 大小均为 28)时,它不再起作用了。这可能是大小或内存错误:
TCHAR szName[] = TEXT("Global\MyFileMappingObject");
所以我的问题是:
如何增加文件或缓冲区的数据大小?如何在文件映射中传递我的对象类的所有成员(两个字符串和 HWND hwndWindow;HANDLE histFile;WIN32_FIND_DATA dataFile)是否还有其他方法可以在两个进程之间共享来自对象的数据。
PS:我阅读了很多论坛,我没有找到我的答案或不明白。
谢谢大家。