简体   繁体   English

地址=通过宏定义的数据

[英]address=data via macro define

#define PORTC *(unsigned char volatile *)(0x1003)

#define DDRC *(unsigned char volatile *)(0x1007)

So I've been trying to read some stuff about embedded C. Initially I thought this macro was a pointer-to-pointer type but then I soon assumed the last star is actually a dereference rather than a type-cast, am I correct? 因此,我一直在尝试阅读一些有关嵌入式C的知识。最初,我认为该宏是指针到指针的类型,但是后来我很快就认为最后一个星实际上是取消引用而不是类型转换,对吗? Dereferencing to the location 0x1003/0x1007. 取消引用位置0x1003 / 0x1007。

It is used like: PORTC = <some hex value> 它的用法如下: PORTC = <some hex value>

Question is what makes this different from a pointer type-cast? 问题是什么与指针类型转换有什么不同? Is there some sort of 'provision' in the C specifications? C规范中是否有某种“规定”? Or am I just an idiot... 还是我只是个白痴...

Also I don't quite know how to phrase this and so I couldn't do a quick search first... 另外我也不知道该如何表达,所以我不能先快速搜索...

No, it is quite a cast. 不,这是一个演员。

First, the memory location (as integer) is cast into an appropriate pointer which is then dereferenced. 首先,将内存位置(作为整数)转换为适当的指针,然后将其取消引用。

It's just the way the C grammar is defined. 这就是定义C语法的方式。

To be a cast, the expression needs parenthesis: (type)sub-expression casts sub-expression to type type . 要进行转换,表达式需要带括号: (type)sub-expressionsub-expression (type)sub-expression转换为type type

Your example, *(unsigned char volatile *)(0x1003) is composed of 2 sub-expressions: 您的示例*(unsigned char volatile *)(0x1003)由2个子表达式组成:

  • a "lonely" star: * “孤独”的明星: *
  • a cast: (unsigned char volatile *)(0x1003) (unsigned char volatile *)(0x1003)(unsigned char volatile *)(0x1003)

The cast is composed of the type inside () and a value. 转换由()内的类型和一个值组成。

So, the whole expression is interpreted as a pointer, then de-referenced to set the memory area pointed to. 因此,将整个表达式解释为一个指针,然后取消引用以设置指向的内存区域。

That code is basically equivalent to: Put <some hex value> in the memory at the address (0x1003) (or whatever the value is). 该代码基本上等同于:将<some hex value>放入内存中的地址(0x1003)(或任何值)。 In some embedded devices (and not only) ports are mapped at memory locations. 在某些嵌入式设备中(不仅是),端口被映射到内存位置。

The cast instructs the compiler that the memory addresses 0x1003 and 0x1007 are to be treated as unsigned char volatile * pointers, and the * dereferencing operator acts on that pointer to fetch the pointed-to value, which in this case is 1 byte. 0x1003指示编译器将内存地址0x10030x1007视为unsigned char volatile *指针,并且*解引用运算符对该指针起作用以获取指向的值,在这种情况下为1个字节。

Applying the unary * makes this expression a valid lvalue (it wouldn't be so without it) which means that it is something you can assign to. 应用一元*使该表达式成为有效的左值(没有它就不会这样),这意味着可以将其赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM