代码之家  ›  专栏  ›  技术社区  ›  Tim unnamed eng

运行时确定C的类型

  •  4
  • Tim unnamed eng  · 技术社区  · 15 年前

    如果变量的类型必须在C中确定为运行时,但变量名是固定的并给定的,那么是否有任何方法可以重用涉及该变量的代码?

    实际上,我在问的是 runtime determine type for C++ .

    如有可能,请举例说明。

    2 回复  |  直到 13 年前
        1
  •  7
  •   Pascal Cuoq    15 年前

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

    您通常通过在C中强制转换来实现泛型。 void* . 例子: the C function qsort .

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

        2
  •  1
  •   Chris Reid    13 年前

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

    推荐文章