【发布时间】:2021-10-25 16:09:30
【问题描述】:
我正在使用 mmap 和 /dev/mem。我在 C 中看到 examples 使用以下模式:
#define OFFSET = ...;
int fd = 0;
void* base;
fd = open("/dev/mem", ...);
base = mmap(..., fd, ...);
// Below is line of interest.
*((uint32_t*)(base + OFFSET)) = 23;
第一个问题 - 这里发生了什么?
看起来我们正在向void* 添加一个偏移值,然后将其转换为uint32_t*,然后为其分配一个数字。为什么我们不能将base 声明为uint32_t*?为什么要在分配它之前施放它?
第二个问题 - 我如何在 C++ 中做到这一点?
以下作品来自网络上的点点滴滴。但这基本上是我尝试用reinterpret_cast 和static_cast 打地鼠,看看哪一个给了我正确的结果并且不会抛出错误或警告。还将void* 替换为uint8_t*,以防止编译器警告我void 指针上的算术。我不知道它为什么起作用,或者它是否是正确的方法。帮我别开枪打自己的脚?
#define OFFSET = ...;
int fd = 0;
uint8_t* base;
fd = open("/dev/mem", ...);
base = reinterpret_cast<uint8_t*>(mmap(..., fd, ...));
*(reinterpret_cast<uint32_t*>(base + OFFSET)) = 23;
【问题讨论】: