[英]shared memory, how to access from another cpp file
What I have done so far: 到目前为止,我所做的是:
main.cpp
using namespace std;
bool *failOver = static_cast<bool*>(mmap(0,sizeof(failOver),
PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANONYMOUS,-1,0));
int main()
{
call of function from function.cpp.
}
function.cpp
extern bool* failOver;
function test()
{
//sem_wait(shared sem)
modify failOver;
//sem_post(shared sem)
}
If I try to compile it, it returns an error: "cannot convert bool
to bool*
in assignment". 如果我尝试编译它,它会返回一个错误:“不能转换bool
到bool*
赋值”。 Also accessing with std::failOver
does not work. 同样,使用std::failOver
访问也不起作用。
How do I access the shared memory variable from other files? 如何从其他文件访问共享内存变量?
You are mixing together a few different problems. 您将几个不同的问题混在一起。
1- bool* failOver
is not a bool
, it is a pointer to bool
; 1- bool* failOver
不是bool
,而是指向bool
的指针; in other words, failOver
represents the memory address where the bool
you are interested in is stored. 换句话说, failOver
表示您感兴趣的bool
存储的内存地址。 If you wanna read the bool
value pointed by failOver
, you have to *dereference` the pointer, ie 如果您想读取failOver
指向的bool
值,则必须“取消引用”指针,即
bool my_value = *failOver;
So, I don't know how mmap
works, but if it returns a void*
, you may want to cast that to bool*
and then to dereference it. 因此,我不知道mmap
工作原理,但是如果它返回void*
,则可能需要将其bool*
为bool*
,然后再取消引用它。 Furthermore, I think you don't want to read sizeof(failOver)
bytes (ie sizeof(bool*)
bytes), but sizeof(bool)
bytes. 此外,我认为您不想读取sizeof(failOver)
字节(即sizeof(bool*)
字节),而是要读取sizeof(bool)
字节。
2- You have to define your variable (ie making room for it in memory) if you want it to be found by another translation unit. 2-如果要由另一个翻译单元查找变量,则必须定义变量(即在内存中为其留出空间)。 To define it, you have to initialize it in the global scope : 要定义它,您必须在全局范围内对其进行初始化:
bool* failOver = 0;
Then, in the other file you can declare it extern
and use it. 然后,在另一个文件中,您可以将其声明为extern
并使用它。
In main.cpp it should be 在main.cpp中应该是
bool *failOver = static_cast<bool*>(mmap(0,sizeof(*failOver),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS,-1,0));
the size was wrong. 大小不对。 In function.cpp 在function.cpp中
extern bool* failOver;
function test()
{
//sem_wait(shared sem)
*failOver = false;
//sem_post(shared sem)
}
Is it as simple as you missing the *
in *failOver
? 就像您在*failOver
丢失*
一样简单吗? Reading Paolo latest answer he's come to the same conclusions. 阅读Paolo的最新答案,他得出了相同的结论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.