简体   繁体   English

使用结构体的字段分配结构体的指针

[英]Assigning a pointer to the structure with pointer to its field

What does struct uart_omap_port *up = (struct uart_omap_port *)port means?. struct uart_omap_port *up = (struct uart_omap_port *)port是什么意思?

Is it similar to container_of macro? 它类似于container_of宏吗?

struct uart_omap_port *up = (struct uart_omap_port *)port;

It means that you "port" pointer variable should be typecast to of type "struct uart_omap_port". 这意味着“端口”指针变量应类型转换为“ struct uart_omap_port”类型。 This is not required in C as it would implicitly do the typecasting(if your port is of void*). 在C中这不是必需的,因为它将隐式进行类型转换(如果您的端口为void *)。 This is not macro it just way(typecasting) the pointer with the different type. 这不是宏,它只是使用不同类型的方式(类型转换)指针。

EDIT 编辑

Code Snippet From Linux/drivers/tty/serial/omap-serial.c 来自Linux / drivers / tty / serial / omap-serial.c的程式码片段

static void serial_omap_enable_ms(struct uart_port *port) {
    .....
    struct uart_omap_port *up = to_uart_omap_port(port);
}


#define to_uart_omap_port(p)    ((container_of((p), struct uart_omap_port, port)))

#define container_of(ptr, type, member) ({                    \
     const typeof(((type *)0)->member)*__mptr = (ptr);    \
     (type *)((char *)__mptr - offsetof(type, member)); })

This is the code which you have reffered. 这是您推荐的代码。 Yes,'to_uart_omap_port' is the MACRO which internally uses 'container_of' and 'offsetof' MACRO. 是的,“ to_uart_omap_port”是内部使用“ container_of”和“ offsetof” MACRO的宏。

This has been written to get the pointer 'up' which is of type 'struct uart_omap_port' from the pointer 'port' of type 'struct uart_port'. 这是为了从类型为“ struct uart_port”的指针“ port”中获取类型为“ struct uart_omap_port”的指针“ up”。 This is bit complicated and you need to check how 'struct uart_port' and 'struct uart_omap_port' been declared. 这有点复杂,您需要检查如何声明“ struct uart_port”和“ struct uart_omap_port”。

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

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