一种标准技术是提供一个快速类型信息变量作为参数
打开它,并通过引用传递所有数据。在函数内部,我们通过显式转换恢复值。编译器不检查void*类型,因此危险在于发送一个函数未处理的类型(分段错误、数据损坏或未知行为结果)。
首先设置所需类型的枚举:
在本例中,我使用约定类型_函数表示返回类型的函数。
enum指令从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 ... */
除一次性功能外
建议使用varargs函数
http://www.eskimo.com/~scs/cclass/int/sx11b.html