所以我试图将一个整数 a =3 从服务器端传递给客户端。问题是,当我在客户端对消息进行 printf 时,显示的值不是 3,而是一个随机数(类似于 19923) .我试图在服务器端通过值(&a)传递a,但显示的值是心形。请查看该通信有什么问题。提前致谢。
//Server
#include <windows.h>
#define BUF_SIZE 256
LPSTR szMapName = "MyFileMappingObject";
int main(void)
{
int a = 3;
HANDLE hMapFile;
LPVOID lpMapAddress;
BOOL bRet;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, /* use swap, not a particular file */
NULL, /* default security */
PAGE_READWRITE, /* read/write access */
0, /* maximum object size (high-order DWORD) */
1024, /* maximum object size (low-order DWORD) */
szMapName); /* name of mapping object */
if (hMapFile == INVALID_HANDLE_VALUE){
printf("CreateFileMapping error %lu",GetLastError());
}
lpMapAddress = MapViewOfFile(
hMapFile, /* handle to map object */
FILE_MAP_ALL_ACCESS, /* read/write permission */
0, /* offset (high-order) */
0, /* offset (low-order) */
0);
if (lpMapAddress == NULL)
printf("MapViewOfFile error");
//ZeroMemory(lpMapAddress, strlen(szMsg) + 1);
CopyMemory(lpMapAddress, a, sizeof(a));
Sleep(10000);
bRet = UnmapViewOfFile(lpMapAddress);
if (bRet == FALSE)
printf("UnampViewOfFile error");
bRet = CloseHandle(hMapFile);
if (bRet == FALSE)
printf("CloseHandle error");
return 0;
}
//Client
#include <windows.h>
#include <stdio.h>
#define BUF_SIZE 256
LPSTR szMapName = "MyFileMappingObject";
int main(void)
{
HANDLE hMapFile;
LPVOID lpMapAddress;
BOOL bRet;
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, /* read/write access */
FALSE, /* do not inherit the name */
szMapName); /* name of mapping object */
if (hMapFile == INVALID_HANDLE_VALUE){
printf("CreateFileMapping error %lu",GetLastError());
return 1;
}
lpMapAddress = MapViewOfFile(
hMapFile, /* handle to map object */
FILE_MAP_ALL_ACCESS, /* read/write permission */
0, /* offset (high-order) */
0, /* offset (low-order) */
0);
if (lpMapAddress == NULL){
printf("MapViewOfFile error %d",GetLastError());
return 1;
}
printf("Message from server is: %d\n", lpMapAddress);
bRet = UnmapViewOfFile(lpMapAddress);
if (bRet == FALSE){
printf("UnampViewOfFile");
return 1;
}
bRet = CloseHandle(hMapFile);
if (bRet == FALSE){
printf("CloseHandle");
return 1;
}
return 0;
}