gpt4 book ai didi

c++ - 与内存映射、c++、ERROR_NOT_ENOUGH_MEMORY 共享结构

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:05 24 4
gpt4 key购买 nike

我试图让我的软件通过内存映射与预先存在的第三方软件进行通信。我被告知要将结构写入由其他软件创建的内存映射文件。我设法打开了该文件,并且肯定已正确创建它,但是当我尝试映射该文件时出现错误 8 (ERROR_NOT_ENOUGH_MEMORY)。

#include "stdafx.h"
#include <Windows.h>

struct MMFSTRUCT
{
unsigned char flags;
DWORD packetTime;
float telemetryMatrix[16];
float velocity[3];
float accel[3];
};

int _tmain(int argc, _TCHAR* argv[])
{
DWORD Time = 0;
HANDLE hMapFile;
void* pBuf;
TCHAR szName[]=TEXT("$FILE$");

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;
}
while(true)
{
pBuf = MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_WRITE, // read/write permission
0,
0,
0);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
MMFSTRUCT test_data;
// define variables here
CopyMemory(pBuf, &test_data, sizeof(MMFSTRUCT));
}
// etc
return 0;
}

MSDN 说,如果共享内存没有被创建它的程序设置为增长,这可能会发生,我应该尝试使用这些函数来设置指针大小:

SetFilePointer(hMapFile, sizeof(MMFSTRUCT) , NULL, FILE_CURRENT);
SetEndOfFile(hMapFile);

但我仍然遇到错误 8,任何帮助将不胜感激,谢谢。

最佳答案

我认为循环内的 MapViewOfFile 毫无意义。那可能是错字?除此之外,您应该将映射到 MapViewOfFile 的内存大小传递给 MapViewOfFile,因为您的文件可能是空的:

if (hMapFile == NULL)
{
_tprintf(TEXT("Could not open file mapping object (%d).\n"),
GetLastError());
return 1;
}

pBuf = MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_WRITE, // read/write permission
0,
0,
sizeof(MMFSTRUCT));
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
return 1;
}
MMFSTRUCT test_data;
// define variables here
CopyMemory(pBuf, &test_data, sizeof(MMFSTRUCT));

UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);

关于c++ - 与内存映射、c++、ERROR_NOT_ENOUGH_MEMORY 共享结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084763/

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