将 void* 作为函数调用而不声明函数指针
我已经搜索过,但找不到任何结果(我的术语可能有问题),所以如果以前有人问过这个问题,请原谅我。
我想知道是否有一种简单的方法可以在 C 中将 void* 作为函数调用,而无需先声明函数指针,然后为函数指针分配地址;
IE。假设要调用的函数是 void(void)
类型,
void *ptr;
ptr = <some address>;
((void*())ptr)(); /* call ptr as function here */
使用上面的代码,我得到错误 C2066:在 VC2008 中转换为函数类型是非法的
如果这是可能的,如何实现对于具有返回类型和多个参数的函数,语法会有所不同吗?
I've searched but couldn't find any results (my terminology may be off) so forgive me if this has been asked before.
I was wondering if there is an easy way to call a void*
as a function in C without first declaring a function pointer and then assigning the function pointer the address;
ie. assuming the function to be called is type void(void)
void *ptr;
ptr = <some address>;
((void*())ptr)(); /* call ptr as function here */
with the above code, I get error C2066: cast to function type is illegal in VC2008
If this is possible, how would the syntax differ for functions with return types and multiple parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的转换应该是:
一般来说,可以通过为函数指针类型创建一个 typedef 来简化这一点:
但是,我应该指出,将普通指针(指向对象的指针)转换为普通指针(指向对象的指针)或从函数指针在标准 C 中并不严格合法(尽管它是常见的扩展)。
Your cast should be:
In general, this can be made simpler by creating a
typedef
for the function pointer type:I should, however, point out that casting an ordinary pointer (pointer to object) to or from a function pointer is not strictly legal in standard C (although it is a common extension).
当转换为函数类型时,我感到非常困惑。 typedef 函数指针类型更容易且更具可读性:
I get awfully confused when casting to function types. It's easier and more readable to typedef the function pointer type:
在 C++ 中:
reinterpret_cast<无效(*)()> (ptr) ()
使用
reinterpret_cast
可以节省一组令人困惑的括号,并且<; >
清楚地将类型与调用本身分开。In C++:
reinterpret_cast< void(*)() > (ptr) ()
The use of
reinterpret_cast
saves you a set of confusing parentheses, and the< >
clearly sets the type apart from the call itself.