一种方法:
就是看着windows的文档写函数呗。哎/。
link: https://blog.csdn.net/tojohnonly/article/details/70246965
“同一块内存区域可能被多个进程同时使用 , 当调用 CreateFileMapping 创建命名的内存映射文件对象时 , Windows 即在物理内存申请一块指定大小的内存区域 , 返回文件映射对象的句柄 hMap ; 为了能够访问这块内存区域必须调用 MapViewOfFile 函数 , 促使 Windows 将此内存空间映射到进程的地址空间中 ; 当在其他进程访问这块内存区域时 , 则必须使用 OpenFileMapping 函数取得对象句柄 hMap , 并调用 MapViewOfFile 函数得到此内存空间的一个映射 , 这样系统就把同一块内存区域映射到了不同进程的地址空间中 , 从而达到共享内存的目的。”
关键函数
需要包含windows头文件:
#include <windows.h>
1) CreateFileMapping:
微软的文档: https://docs.microsoft.com/en-us/previous-versions/aa914748(v=msdn.10)?redirectedfrom=MSDN
This function creates a named or unnamed file-mapping object for the specified file.
2) MapViewOfFile
https://docs.microsoft.com/en-us/previous-versions/aa914405(v%3dmsdn.10)
This function maps a view of a file into the address space of the calling process.
3)OpenFileMapping
Code:
写数据的进程:
#include "stdafx.h"
#include <windows.h>
#include <string.h>
//#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
using namespace std;
#define BUF_SIZE 4096
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
// 定义共享数据
char szBuffer[] = "Hello xxxx";
// 创建共享文件句柄
HANDLE hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // 物理文件句柄
NULL, // 默认安全级别
PAGE_READWRITE, // 可读可写
0, // 高位文件大小
BUF_SIZE, // 地位文件大小
L"ShareMemory" // 共享内存名称
);
// 映射缓存区视图 , 得到指向共享内存的指针
LPVOID lpBase = MapViewOfFile(
hMapFile, // 共享内存的句柄
FILE_MAP_ALL_ACCESS, // 可读写许可
0,
0,
BUF_SIZE
);
// 将数据拷贝到共享内存
strcpy((char*)lpBase, szBuffer);
// 线程挂起等其他线程读取数据
Sleep(10000);
// 解除文件映射
UnmapViewOfFile(lpBase);
// 关闭内存映射文件对象句柄
CloseHandle(hMapFile);
return 0;
}
读数据的进程:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
#define BUF_SIZE 4096
int main()
{
// 打开共享的文件对象。 注意: "ShareMemory"要与写数据进程的字符串相同!
HANDLE hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, NULL, L"ShareMemory");
if (hMapFile)
{
LPVOID lpBase = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
// 将共享内存数据拷贝出来
char szBuffer[BUF_SIZE] = { 0 };
strcpy(szBuffer, (char*)lpBase);
printf("%s", szBuffer);
// 解除文件映射
UnmapViewOfFile(lpBase);
// 关闭内存映射文件对象句柄
CloseHandle(hMapFile);
}
else
{
// 打开共享内存句柄失败
printf("OpenMapping Error");
}
return 0;
}
调试时遇到的问题:
https://blog.csdn.net/leowinbow/article/details/82380252
所以修改了Vs默认的stdfx.h文件,加了一行#define _CRT_SECURE_NO_WARNINGS
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <tchar.h>
相关:
https://www.cnblogs.com/xuandi/p/5673917.html
Boost库实现共享内存:
good: https://www.jianshu.com/p/56efa9d1500a