用C匿名结构在Unix内核中发现 [英] Anonymous Structures in C found in Unix Kernel

查看:100
本文介绍了用C匿名结构在Unix内核中发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读在Unix V6狮子评论。我遇到了这些片段,这是我从来没有见过在C语言中使用。笔者确实提供某种解释,但可能有人向我解释这里发生了什么?

I have started reading the Lions Commentary on Unix v6. I came across these snippets, which I have never seen used in the C language. The author does provide some sort of an explanation, but could someone explain to me what is happening here?

params.h

SW 0177570
...... 
struct { int integ; };

在此使用 UNIX / prf.c

if(SW->integ == 0)

由作者解释

SW 是pviously定义$ P $作为值
  0177570.这是一个内核地址
  只读寄存器存储的
  控制台开关寄存器的设置。
  该语句的意思很明显:获得
  在位置0177570内容,看看他们是否
  是零。的问题是要在离preSS此
  C.在code 如果(SW == 0)也不会传达这个意思。明确地
   SW 是这应该是一个指针值
  取消引用。编译器可能已经
  改为接受
  如果(SW-GT&; == 0)
  但因为它的立场,这是语法不正确。通过发明一个虚拟结构,
  一个元素 INTEG ,程序员已经找到了满意的解决办法
  他的问题。

SW is defined previously as the value 0177570. This is the kernel address of a read only processor register which stores the setting of the console switch register. The meaning of the statement is clear: get the contents at location 0177570 and see if they are zero. The problem is to express this in C. The code if (SW == 0) would not have conveyed this meaning. Clearly SW is a pointer value which should be dereferenced. The compiler might have been changed to accept if (SW-> == 0) but as it stands, this is syntactically incorrect. By inventing a dummy structure, with an element integ , the programmer has found a satisfactory solution to his problem.

我的问题主要是如何工作的呢?当编译器看到 SW-> INTEG ,它是如何关联 SW 通过匿名结构

My question mainly is how does this work? When the compiler sees SW->integ, how does it associate SW with the anonymous structure?

推荐答案

IIRC,古老的C编译器保存在一个单一命名空间,而不是所有的字段名称(如 INTEG )创建每结构 A空间键入。他们也没有结构指针和 INT 指针之间的区别,让每一个指针都有一个对应其第一的sizeof(INT)字节INTEG 字段。由于 INTEG 是在结构,且类型为 INT SW-方式> INTEG 对应 *((INT *)SW)

IIRC, ancient C compilers kept all field names (such as integ) in a single namespace instead of creating a namespace per struct type. They also did not distinguish between struct pointers and int pointers, so that every pointer has an integ field corresponding to its first sizeof(int) bytes. Since integ is the first value in a struct and has type int, SW->integ corresponds to *((int *)SW).

这篇关于用C匿名结构在Unix内核中发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆