C库和函数指针 [英] C libraries and function pointers

查看:72
本文介绍了C库和函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C库,该库声明了以下类型的函数

void SomeFunction(int a,int(* fp)());

但是,在库中的用法中,它们似乎传递带有额外参数的函数指针
例如. int(* fp)(char *,int)


在C中似乎没问题.

但是,编译C ++(gcc)不允许这样做.

任何有关哪种线索将是最简单的解决此问题的方法.

我当时正在考虑进行强制转换,但是不确定要使用哪种强制转换类型-static_cast或reinterpret_cast?

I have a C library which declares a function of the following type

void SomeFunction(int a, int(*fp)()) ;

However in the usage within the library , they seem to pass function pointers that take extra parameters
eg. int (*fp)(char * , int)


It seems to be ok in C .

However compiling C++ ( gcc) , this isnt allowed.

Any clues as to which would be the most easiest way to fix this .

I was thinking of casting this but was unsure about which casting type to use - static_cast or reinterpret_cast ?

推荐答案

在C中,当函数声明时没有像int这样的任何参数fun(),这意味着它可以接受可变数量的参数.如果您不希望函数在C中采用任何参数,则必须将其显式声明为int fun(void).

在C ++中,这种情况发生了变化.没有任何参数声明的函数等同于以void声明.可变参数将需要省略号(...)作为参数.

因此,对于C ++,您将需要使用省略号声明它,如以下链接中所述-
http://msdn.microsoft.com/en-us/library/fxhdxye9 (v = vs.80).aspx [
In C, when a function is declared without any parameters like int fun(), it means it can take variable number of parameters. If you don''t want the function to take any parameters in C, you must explicitly declare it as int fun(void).

In C++, this changed. Functions declared without any parameters are equivalent to being declared with void. Variable arguments would need the ellipsis (...) as parameter.

So for C++ you would need to declare it with ellipsis as mentioned in the following link -
http://msdn.microsoft.com/en-us/library/fxhdxye9(v=vs.80).aspx[^]


您可以执行此操作的主要原因是,大多数C语言的类型都不如C ++强. IE.如果您要违反"某些内容,则不需要C ++中那么多的类型转换.

reinterpret_cast与static_cast [ ^ ]
The main reason you can do this is because most flavors of C is not as strongly typed as C++. I.e. you don''t need as many type-casts as you would in C++ if you want to ''violate'' something.

reinterpret_cast vs static_cast[^]


typedef int (*FNPARAM)();

int OtherFunc(char* lpc,int i)
{
  return 0;
}

void main()
{
  SomeFunction(1,(FNPARAM)OtherFunc);
}


就这样吧.


Thats it, regards.


这篇关于C库和函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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