Windows编程怎么创建共享内存
时间: 2024-05-27 08:10:27 浏览: 91
请参考以下代码示例,使用Visual C++编写:
#include <stdio.h>
#include <windows.h>
#define BUF_SIZE 255
#define FILE_MAP_NAME "ShareMem"
int main()
{
HANDLE hMapFile;
LPCTSTR pBuf;
char szMsg[BUF_SIZE];
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
FILE_MAP_NAME); // name of mapping object
if (hMapFile == NULL)
{
printf("Could not create file mapping object (%d).\n", GetLastError());
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
printf("Could not map view of file (%d).\n", GetLastError());
CloseHandle(hMapFile);
return 1;
}
printf("Enter message: ");
fgets(szMsg, BUF_SIZE, stdin);
CopyMemory((PVOID)pBuf, szMsg, (strlen(szMsg) + 1) * sizeof(TCHAR));
printf("Message written to memory: %s", pBuf);
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
阅读全文