[英]pointer in boost shared memory object
I am dealing with boost::interprocess::shared_memory_object
and what I'm trying to achieve is like this. 我正在处理boost::interprocess::shared_memory_object
而我想要达到的目标是这样的。
I define my own class which is called SharedMemory
and in it, there is a method called CreateSharedMemory()
which creates a memory block. 我定义了自己的类,称为SharedMemory
,其中有一个名为CreateSharedMemory()
的方法,该方法创建一个内存块。 I need to keep three arrays Foo a1[SIZE], Foo a2[SIZE]
and Foo a3[SIZE]
in this memory block such that I can consistently write data into them. 我需要在此内存块中保留三个数组Foo a1[SIZE], Foo a2[SIZE]
和Foo a3[SIZE]
,以便可以将数据连续写入其中。 Foo
is my own defined class. Foo
是我自己定义的类。 To access these three arrays, I need to get their address in my process. 要访问这三个数组,我需要在过程中获取它们的地址。 So I pass three pointers Foo *p1, *p2, *p3
to this method to record their addresses. 因此,我将三个指针Foo *p1, *p2, *p3
传递给此方法以记录其地址。 Everything goes well in this method but once it steps out this method, p1, p2, p3
point to the wrong address. 此方法一切正常,但一旦退出该方法,则p1, p2, p3
指向错误的地址。 Can anyone help? 有人可以帮忙吗?
// Foo.h
class Foo
{
double f[MAX_SIZE];
char c[MAX_SIZE];
}
// SharedMemory.cpp
void SharedMemory::CreateSharedMemory(Foo *p1, Foo *p2, Foo *p3)
{
boost::interprocess::shared_memory_object shm
(boost::interprocess::create_only
,"foo" //name
,boost::interprocess::read_write
);
shm.truncate(blockSize);
//Map the whole shared memory in this process
boost::interprocess::mapped_region region(shm, boost::interprocess::read_write);
//Write all the memory to 0
memset(region.get_address(), 0, region.get_size());
// assign address
p1 = static_cast<Foo *>(region.get_address());
p2 = static_cast<Foo *>(region.get_address() + blockSize / 3);
p3 = static_cast<Foo *>(region.get_address() + 2 * blockSize / 3);
// p1, p2, p3 point to the correct address here
}
// p1, p2, p3 point to the wrong address once it steps out CreateSharedMemory()
You must pass a reference to Foo pointer. 您必须传递对Foo指针的引用。 Like: 喜欢:
void SharedMemory::CreateSharedMemory(Foo* & p1, Foo* & p2, Foo* &p3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.