我正在使用boost :: interprocess在进程之间共享对象。我有两个文件,一个“ server.cpp”,它生成一个struct对象,并将该对象传递给具有int索引的映射;还有一个“ client.cpp”文件,它检索内存数据并遍历数据,并输出到控制台。
该结构如下所示:
struct mydata o {
string MY_STRING;
int MY_INT;
};
Run Code Online (Sandbox Code Playgroud)
和对象:
mydata o;
o.MY_STRING = "hello";
o.MY_INT = 45;
Run Code Online (Sandbox Code Playgroud)
服务器和客户端均可正确编译。但是由于某种原因,如果我尝试访问客户端中的字符串而不是浮点数或整数,则客户端可执行文件会引发分段错误。例如,下面的second.MY_INT将退出控制台,但是second.MY_STRING在运行时引发此错误。
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>
#include <iostream>
#include <string>
#include "objects.cpp" //definitions for objects
using std::string;
using namespace boost::interprocess;
int main ()
{
try
{
managed_shared_memory segment(open_or_create, "SharedMemoryName",65536);
//Again the map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>, so the allocator must allocate that pair.
typedef int KeyType;
typedef order MappedType;
typedef std::pair<const int, order> ValueType;
//Assign allocator
typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator;
//The map
typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MySHMMap;
//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc_inst (segment.get_segment_manager());
//access the map in SHM through the offset ptr
MySHMMap :: iterator iter;
offset_ptr<MySHMMap> m_pmap = segment.find<MySHMMap>("MySHMMapName").first;
iter=m_pmap->begin();
for(; iter!=m_pmap->end();iter++)
{
//std::cout<<"\n "<<iter->first<<" "<<iter->second;
std::cout<<iter->first<<" "<<iter->second.MYINT<<" "<<iter->second.MYSTRING<<"\n";
}
}catch(std::exception &e)
{
std::cout<<" error " << e.what() <<std::endl;
shared_memory_object::remove("SharedMemoryName");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
运行时的错误:
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)
我很确定服务器正在将整个对象传递到内存,并且客户端可以检索它(因为我可以访问某些对象属性),而这仅仅是一个格式问题。
小智 1
之前海报中的一些重要信息让我得出了自己的简单答案。在结构体中使用char数组,然后将其读入字符串,如下所示:
std::cout<<iter->first<<" "<<iter->second.ORDERTYPE<<" "<<string(iter->second.MYID)<<"\n";
Run Code Online (Sandbox Code Playgroud)
这是我所说的结构:
struct order {
char MYID[100];
int ORDERTYPE;
char DATE_UPDATED[64];
};
order o
Run Code Online (Sandbox Code Playgroud)
这是我将结构传递到内存中的方法:
m_pmap->insert(std::pair<const int, order>(i, (order)o));
Run Code Online (Sandbox Code Playgroud)
现在我能够将包含各种类型(包括字符串)的结构映射写入内存,并从内存中检索它们。