gpt4 book ai didi

c - MapViewOfFile 向子进程发送整数

转载 作者:行者123 更新时间:2023-11-30 15:53:46 27 4
gpt4 key购买 nike

所以我试图将一个整数 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;
}

最佳答案

这是不正确的:

printf("Message from server is: %d\n", lpMapAddress);

因为 lpMapAddress 的类型为 LPVOID(a void*),因此这将打印 lpMapAddress 的内存地址code> 点,不是整数值。 (请注意,必须使用 %p 来打印指针值)。

基于将 int 写入共享内存的技术:

CopyMemory(lpMapAddress, a, sizeof(a));

提取int将是相反的:

int read_a;
CopyMemory(&read_a, lpMapAddress, sizeof(read_a));
printf("Message from server is: %d\n", read_a);

请注意,以下行中缺少格式说明符:

printf("CreateFileMapping error",GetLastError());

应该是:

printf("CreateFileMapping error: %lu", GetLastError());

关于c - MapViewOfFile 向子进程发送整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13513908/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com