C++ 共享内存使用例子
时间: 2024-08-13 16:09:12 浏览: 71
在C++中,共享内存是一种进程间通信(IPC,Inter-Process Communication)技术,它允许不同进程直接访问同一块内存区域,从而提高了数据交换的效率。这种技术通常用于高性能应用,如游戏引擎、实时系统和多线程协作。
以下是一个简单的C++共享内存使用例子,使用`boost::interprocess`库:
```cpp
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
// 创建共享内存
std::string sharedMemoryName = "SharedMemoryExample";
boost::interprocess::size_t size = 100; // 100字节的内存大小
boost::interprocess::error_code ec;
boost::interprocess::shared_memory_object shm(boost::interprocess::create_only, sharedMemoryName, boost::interprocess::read_write);
if (ec) {
std::cerr << "Error creating shared memory: " << ec.message() << std::endl;
} else {
// 如果创建成功,调整其大小
shm.truncate(size);
if (!shm.is_open()) {
std::cerr << "Error truncating shared memory." << std::endl;
return;
}
// 映射共享内存到进程地址空间
boost::interprocess::mapped_region region(shm, boost::interprocess::read_write);
char* sharedMemory = static_cast<char*>(region.get_address());
// 在进程中写入数据
std::cout << "Writing to shared memory: Hello, World!" << std::endl;
std::strcpy(sharedMemory, "Hello, World!");
// 另一进程读取数据
std::string receivedData;
std::strncpy(receivedData, sharedMemory, size);
std::cout << "Reading from shared memory: " << receivedData << std::endl;
// 释放映射区域
region.unmap();
}
// 关闭共享内存
shm.close();
```
阅读全文