C 这行代码在做什么?是铸造吗?
C what is this line of code doing? Is it casting?
所以我正在关注在线教程(如果重要的话,关于 OS 开发),我看到这行 c 代码无效。这是一个简化版本:
void function1(struct regs *r) {
void (*handler)(struct regs *r); // What happened here?
// do things with void *handler
}
那一行发生了什么?它声明了一个变量
void *handler
但它做了类似演员表的事情?但它看起来不像演员。那里刚刚发生了什么?
void (*handler)(struct regs *r);
将 handler
声明为指向需要类型 struct regs *
和 returns 类型参数的函数的指针 void
.
void (*handler)(struct regs *r);
这种特殊形式是函数指针的声明。这里没有演员表。
handler
是一个指向函数的指针,该函数接受类型为 struct regs *
和 returns 的参数。
可以这样使用:
void foo(struct regs *r)
{
/* a function that takes an argument of type
* struct regs * and returns nothing
*/
}
void (*handler)(struct regs *r);
handler = foo; // assign foo to handler object
handler(NULL); // call the function, here with a null pointer
// to simplify the example
该行正在声明一个名为 handler
的变量。相当于
T * handler;
如果 T
是 void(struct regs *)
。 (该行还影响类型 struct regs
的声明。)
函数指针看起来有点奇怪。在这种情况下,没有进行强制转换或赋值 - 这只是一个变量声明。
void (*<variable name>)(<function params>);
在您上面的示例中,<variable name>
是 handler
,<function params>
是 struct regs *r
。
所以我正在关注在线教程(如果重要的话,关于 OS 开发),我看到这行 c 代码无效。这是一个简化版本:
void function1(struct regs *r) {
void (*handler)(struct regs *r); // What happened here?
// do things with void *handler
}
那一行发生了什么?它声明了一个变量
void *handler
但它做了类似演员表的事情?但它看起来不像演员。那里刚刚发生了什么?
void (*handler)(struct regs *r);
将 handler
声明为指向需要类型 struct regs *
和 returns 类型参数的函数的指针 void
.
void (*handler)(struct regs *r);
这种特殊形式是函数指针的声明。这里没有演员表。
handler
是一个指向函数的指针,该函数接受类型为 struct regs *
和 returns 的参数。
可以这样使用:
void foo(struct regs *r)
{
/* a function that takes an argument of type
* struct regs * and returns nothing
*/
}
void (*handler)(struct regs *r);
handler = foo; // assign foo to handler object
handler(NULL); // call the function, here with a null pointer
// to simplify the example
该行正在声明一个名为 handler
的变量。相当于
T * handler;
如果 T
是 void(struct regs *)
。 (该行还影响类型 struct regs
的声明。)
函数指针看起来有点奇怪。在这种情况下,没有进行强制转换或赋值 - 这只是一个变量声明。
void (*<variable name>)(<function params>);
在您上面的示例中,<variable name>
是 handler
,<function params>
是 struct regs *r
。