0
我正在处理boost::interprocess::shared_memory_object
,我试图实现的是这样的。提升共享内存对象中的指针
我定义了我自己的类,它被称为SharedMemory
,其中有一个方法 ,它叫做CreateSharedMemory()
,它创建一个内存块。我需要在这个内存块中保留三个数组Foo a1[SIZE], Foo a2[SIZE]
和Foo a3[SIZE]
,这样我就可以一直向它们写入数据。 Foo
是我自己定义的类。要访问这三个数组,我需要在我的过程中获得他们的地址。所以我通过三个指针Foo *p1, *p2, *p3
这个方法来记录他们的地址。在这种方法中一切都很顺利,但一旦它退出这种方法,p1, p2, p3
指向错误的地址。谁能帮忙?
// 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()
你是对的!谢谢! – Chitanda 2015-03-03 05:10:44