5

如果变量的类型必须在 C 中确定为运行时,但变量名称是固定的并给出的,有没有办法重用涉及变量的代码?

实际上,我是在询问运行时确定 C++ 类型的 C 对应情况。

如果可能,请举一些例子。

4

2 回答 2

8

C 语言没有面向对象的特性,因此在 C++ 中询问对象的运行时类型是有意义的。

您通常通过转换到和从来实现 C 中的泛型void*。示例:C 函数 qsort

如果您的问题是关于在运行时确定void*指针指向的实际类型,那是不可能的。大多数编译器根本不存储这些信息。

于 2010-01-15T09:57:15.087 回答
2

一种标准技术是提供一个快速类型信息变量作为参数并打开它,并通过引用传递所有数据。在函数内部,我们通过显式转换来恢复值。编译器未检查 void* 类型,因此危险在于发送函数未处理的类型(分段错误、数据损坏或未知行为结果)。首先设置您需要的类型的枚举:

在这种情况下,我使用约定 TYPE_FUNCTION 来表示返回类型的函数。

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 ... */

除了一次性函数,建议使用可变参数函数 http://www.eskimo.com/~scs/cclass/int/sx11b.html

于 2012-05-29T16:17:19.673 回答