语法混淆与创建新的结构类型

时间:2015-03-20 13:08:41

标签: c pointers struct callback typedef

    struct I2C_CALLBACK_STRUCT
    {
        HANDLE  (*I2C_OpenDevice)(UINT32 port, UINT32 freq);
        BOOLEAN  (*I2C_CloseDevice)(HANDLE handle);
    };

    typedef struct I2C_CALLBACK_STRUCT  I2C_CALLBACKS_T,    *I2C_CALLBACKS_PTR;

    static const I2C_CALLBACKS_T I2C_Callback =
    {
        OpenI2CPort,
        CloseI2CPort,
    };

有人可以单步执行上述代码并解释发生了什么吗?我理解用函数指针填充结构,但是我不明白当你使用typedef来创建新类型I2C_CALLBACKS_T*I2C_CALLBACKS_PTR时会发生什么。另外,我不理解创建I2C_Callback时使用的语法ie。为什么使用等号,因为这不是我熟悉的东西

我为漫不经心而道歉,我不确定如何说出我的查询。

2 个答案:

答案 0 :(得分:0)

1)typedef

您正在使用typedef创建两种新类型I2C_CALLBACKS_TI2C_CALLBACKS_PTR。这样做是为了在定义结构之前不必编写struct关键字:

I2C_CALLBACKS_T a; // shorter
struct I2C_CALLBACK_STRUCT a; //longer

类型I2C_CALLBACKS_PTR很有用,因为您不必显式定义指向结构的指针:

I2C_CALLBACKS_PTR a, b, c; // shorter
I2C_CALLBACKS_T *a, *b, *c; // longer

2)结构初始化

然后,I2C_Callback struct的函数指针才会映射到OpenI2CPortCloseI2CPort函数。

答案 1 :(得分:0)

如果删除所有“垃圾”字符,可能会更清楚:

// structure decalaration
struct callback
{
  FUNCPTR1 function1;
  FUNCPTR2 function2;
};

// getting rid of always typing `struct` and using a more convenient name
typedef struct callback CALLBACK;
typedef struct callback *CALLBACKPTR; // this one is bad behaviour if used, disturbing the reader of your code

// defining a callback-variable with initialization
CALLBACK c = {fun1, fun2};
// the same:
struct callback c = {fun1, fun2};
// which is, more-or-less, equivalent to: (if it is used inside a scope of afunction):
struct callback c;
c.function1 = fun1;
c.function2 = fun2;

equal - 符号将被视为assignment - 符号。