如何口罩适用于一个const void *的地址? [英] How to apply a mask to a const void* address?
问题描述
我在一个嵌入式目标工作,要定义内存池。
I work on an embedded target and want to define memory pools.
内存地址重新psented为 $ P $无效*
。然而,在特定情况下,这些地址被缓存,我想取消缓存他们直接获得真正的硬件地址。
Memory addresses are represented as void*
. However in a particular case, those addresses are cached and I want to uncache them to get directly the "real" hardware address.
我想定义 memory_area
的起始地址(这仅仅是一个标记):
I want to define the address of the beginning of memory_area
(which is just a marker):
#define UNCACHE_MASK 0xABCDEF12UL // Value of the mask to apply
extern uint32_t memory_area; // Global, defined somewhere else
const void * virtual_address = &memory_area; // OK
const void * real_address =
(void*)(virtual_address | UNCACHE_MASK); // guilty line
不幸的是, GCC
不会让我这样做:
error: invalid operands to binary | (have 'const void *' and 'long unsigned int')
在绝望中我尝试:
const void * real_address =
(void*)(((uint32_t)virtual_address) | UNCACHE_MASK); // guilty line
在徒劳的:
error: initializer element is not constant
我真的想保持常量
安全:这是可以实现的?
I really want to keep the const
for safety : is it achievable ?
- 我使用
GCC
V4.9(与-std = gnu99
和大量的-Wxxx
Linux上的标志)。 - 摘录是从
.H
文件,变量是全局。
- I am using
gcc
v4.9 (with-std=gnu99
and a lot of-Wxxx
flags) on Linux. - The excerpt is from a
.h
file, variables are "global".
推荐答案
您可以将这个使用按位或前$ P $函数内pssion。你不能在全局范围内做初始化为已示出,因为确实的值是不知道的编译器(也许在C ++中,但不是在C)。如果添加石膏和移动分配的功能范围内,它会工作。
You can assign this using your bitwise-OR expression inside a function. You cannot do the initialization at global scope as you have shown, because indeed the value is not known to the compiler (maybe in C++, but not in C). If you add the casts and move the assignment inside a function scope, it will work.
当你这样说:
const void * real_address
这意味着real_address是指向未知类型的常量内存。如果你希望指针也是不可修改(除了它所指向的),你可以这样做:
It means "real_address is a pointer to constant memory of unknown type." If you want the pointer to also not be modifiable (in addition to what it points to), you can do this:
const void * const real_address
但你不会因为你需要做的是能够初始化函数内。我想你可以抛弃函数内部的常量性,但是这可能甚至不合法的温度。
But then you won't be able to initialize it inside a function as you need to do. I suppose you could cast away the constness inside the function, but this may not even be legal in C.
这篇关于如何口罩适用于一个const void *的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!