运行时确定C的类型

运行时确定C的类型,c,runtime-type,C,Runtime Type,如果变量的类型必须在C中确定为运行时,但变量名是固定的和给定的,那么有没有办法重用涉及该变量的代码 事实上,我是在问C对应的情况 如果可能的话,请给出一些例子。 < P> C语言没有面向对象的特性,这使得在C++中询问对象的运行时类型是有意义的。 您通常通过在void*之间进行强制转换来实现C中的泛型。示例: 如果您的问题是在运行时确定实际类型avoid*指针指向什么,那么这是不可能的。大多数编译器根本不存储这些信息。一种标准技术是提供一个快速类型信息变量作为参数 打开它,通过引用传递所有数据。

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

事实上,我是在问C对应的情况


如果可能的话,请给出一些例子。

< P> C语言没有面向对象的特性,这使得在C++中询问对象的运行时类型是有意义的。 您通常通过在
void*
之间进行强制转换来实现C中的泛型。示例:


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

一种标准技术是提供一个快速类型信息变量作为参数 打开它,通过引用传递所有数据。在函数内部,我们通过显式转换恢复值。编译器未检查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函数