复杂的C演员解释
我想弄清楚以下 C 代码的作用是什么?
((void(*)())buf)();
其中“buf”是一个 char
数组。
I'm trying to figure out what the following code in C does?
((void(*)())buf)();
where 'buf' is a char
array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
让我们一步一步来。
这是一个指向函数的指针,该函数接受未指定的参数并且没有返回值。
只需将 buf 转换为该函数指针类型。最后
调用该函数。
所以整个语句是“将
buf
解释为指向不带参数的void
函数的指针,并调用该函数。”Let's take it one step at a time.
This is a pointer to a function that takes unspecified arguments and has no return value.
simply casts buf to this function pointer type. Finally,
calls this function.
So the entire statement is "interpret
buf
as a pointer to avoid
function without arguments, and call that function."它将
buf
转换为void(*)()
类型的函数指针(一个不返回任何内容/void 并接受未指定参数的函数)并调用它。ANSI 标准实际上并不允许将普通数据指针转换为函数指针,但您的平台可能允许。
It casts
buf
to a function pointer of typevoid(*)()
(A function returning nothing/void and taking unspecified arguments) and calls it.The ANSI standard does not really allow the casting of normal data pointers to function pointers, but your platform may allow it.
当我遇到令人难以置信的声明时,我倾向于使用“cdecl”命令。示例:
虽然在某些情况下我确实希望有一个工具可以解释“cdecl”的输出:/
I tend to use the "cdecl" command when I come across a mind boggling declaration. Example:
Although there are cases where I do wish that there's a tool out there that explains the output of "cdecl" :/
这会将
buf
转换为void (*)()
类型,这是一个指向接受未指定参数且不返回任何内容的函数的指针。然后它调用该地址(最右边的两个括号)处的函数。This casts
buf
to the typevoid (*)()
, a pointer to a function that takes unspecified parameters and returns nothing. Then it calls the function at that address (the two rightmost parentheses).它将 buf 转换为函数指针,该指针接受未指定的参数并调用它。
It casts
buf
into a function pointer, that takes unspecified arguments, and calls it.我猜想在很多情况下,它都会使机器崩溃。
否则,它将数组视为指向返回 void 的函数的指针并调用它。
I would guess that in many circumstances, it crashes the machine.
Otherwise, it treats the array as a pointer to a function that returns void and invokes it.
你可能会发现“专家c编程”是一本很好的读物——如果我没记错的话,解压这类东西在其中一章中。我已经很久没有读过这本书了,但我记得当时我认为这是值得的。
http://www.amazon.com/Expert-Programming-Peter-van-Linden/ dp/0131774298
You might find "expert c programming" a good read - unpacking this kind of thing is in one of the chapters, if I remember right. It's a long time since I read it, but I remember thinking it was worth the effort at the time.
http://www.amazon.com/Expert-Programming-Peter-van-Linden/dp/0131774298
lsc 提到有一个在线版本的“cdecl”工具,您可能会觉得有用:http://www.cdecl .org/
There is an online version of the 'cdecl' tool that lsc mentioned that you might find useful : http://www.cdecl.org/
调用函数指针。该函数没有参数。
函数指针 - 维基百科
calls a function pointer. the function has no arguments.
Function Pointer - Wikipedia