题
解决方案
在C语言不具有面向对象的特性,使得它有意义询问在C ++中的对象的运行时类型。
您通常通过铸造,并从void*
实现用C泛型。例如:。 C函数的qsort
如果你的问题是关于在运行时间确定什么实际类型void*
指针指向,那是不可能的。的信息被简单地不被大多数编译器存储在所有。
其他提示
一个标准技术是提供一种快速型信息变量作为参数 并在该切换,并且通过引用传递的所有数据。在函数内部,我们恢复用明确的转换价值。空隙*类型由编译器,危险发出了一个类型,它是由函数(分段错误,数据损坏或未知的行为结果)未处理选中。 通过设置你需要的类型的枚举开始:
在这种情况下,我使用的惯例TYPE_FUNCTION来表示函数返回一个类型。
在枚举指令从0选择连续整数, 或者您可以指定每个枚举它自己的int值。
typedef enum D_types {
ANINT, // don't use actual system type names
AFLOAT,
ADOUBLE,
ASTRING,
MY_STRUCT=100,
MY_STRUCT2=200
VOID_FUNCTION=1000,
INT_FUNCTION = 2000,
STRUCT_FUNCTION=3000
} DATATYPE;
/* an f_int is a function pointer to a function */
typedef int (*f_int)(int, void* );
在您的函数定义你通过引用和类型发送两个数据 并在使用前将它转换为正确的类型:
int myfunction ( DATATYPE dt, void* data, )
{
int an_int = 0;
int * ip; // typed pointers for casting of the void pointer data
double * dp;
char * sp;
struct My_struct * msp;
struct My_struct_2 * ms2p;
f_int fp;
...
switch (dt){
case ANINT:
ip = (int*) data; // only pointers can be assigned void pointer values.
int i = *ip // dereference of typed pointer, no dereferencing void pointers.
...
break;
case ADOUBLE:
dp = (double*) data;
double d = *dp;
...
break;
case ASTRING:
char * s = strdup( (char*) data); // cast to char pointer allowed (pointer->pointer)
...
break;
case MY_STRUCT:
msp = ( struct My_Struct *) data;
char* ms_name = msp->name; // if my_struct has a name string ...
float dollarvalue = msp->dvalue;
...
case INT_FUNCTION:
fp = (f_int)data;
an_int = fp( ANINT, 5);
}
return an_int;
}
您可能已经猜到,这是玩火柴在花炮厂, 而不是鼓励作为一个不断实践。
在你的代码,你会说它是这样的:
double pi =3.14159;
int g = myfunction( ADOUBLE, &pi ); // pass by reference, not value
int j = myfunction (ASTRING , "HEY NOW" ); //C strings pass by ref normally
f_int myfunc = myfunction; // a function pointer (ref to the functions address )
int r = myfunction ( INT_FUNCTION, myfunc ); /* function as a parameter ... */
其他比一次性功能 它建议使用可变参数功能 http://www.eskimo.com/~scs/cclass/int/sx11b html的
不隶属于 StackOverflow