与创建新结构类型的语法混淆
syntax confusion with creating a new struct type
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
即时使用的语法。为什么使用等号,因为这不是我熟悉的东西
很抱歉,我的话题太啰嗦了,我不确定表达我的查询的最佳方式。
1) typedef
您使用 typedef
所做的是创建两种新类型,I2C_CALLBACKS_T
和 I2C_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
结构的函数指针被映射到 OpenI2CPort
和 CloseI2CPort
函数。
如果您删除所有 "garbage" 字符,例如:
,也许会更清楚
// 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
-符号。
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
即时使用的语法。为什么使用等号,因为这不是我熟悉的东西
很抱歉,我的话题太啰嗦了,我不确定表达我的查询的最佳方式。
1) typedef
您使用 typedef
所做的是创建两种新类型,I2C_CALLBACKS_T
和 I2C_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
结构的函数指针被映射到 OpenI2CPort
和 CloseI2CPort
函数。
如果您删除所有 "garbage" 字符,例如:
,也许会更清楚// 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
-符号。