C语言中的互连结构和回调
我需要在C中定义一个结构和回调函数类型,如下所示:C语言中的互连结构和回调,c,coding-style,callback,compiler-errors,C,Coding Style,Callback,Compiler Errors,我需要在C中定义一个结构和回调函数类型,如下所示: typedef void (*callback)(struct XYZ* p); struct { int a; int b; callback cb; } XYZ; 现在这段代码不会编译,因为每个定义都需要另一个。 我的意思是,如果回调定义先出现,它将不会编译,因为它需要定义结构。类似地,如果首先定义结构,则需要定义回调。也许这是一个愚蠢的问题,但有没有干净的方法来解决这些问题 目前我的想法是使用void*作为回调
typedef void (*callback)(struct XYZ* p);
struct {
int a;
int b;
callback cb;
} XYZ;
现在这段代码不会编译,因为每个定义都需要另一个。
我的意思是,如果回调定义先出现,它将不会编译,因为它需要定义结构。类似地,如果首先定义结构,则需要定义回调。也许这是一个愚蠢的问题,但有没有干净的方法来解决这些问题
目前我的想法是使用void*作为回调参数,并将其类型转换为回调中的struct XYZ。有什么想法吗?在函数
typedef
之前声明struct
(尚未定义它):
struct XYZ;
typedef void (*callback)(struct XYZ* p);
struct XYZ { // also fixed an error where your struct had no name
int a;
int b;
callback cb;
};
类似于声明函数原型并在其定义之前调用它。我建议使用以下方法:
typedef struct xyz // xyz is a struct tag, not a type
{
int a;
int b;
void (*callback) (struct xyz* p); // this definition is local, "temporary" until the function pointer typedef below
} xyz_t; // xyz_t is a type
typedef void (*callback_t) (xyz_t* p);
现在,就调用方而言,您的结构相当于:
// This is pseudo-code used to illustrate, not real C code
typedef struct
{
int x;
int y;
callback_t callback;
} xyz_t;
用法示例:
void func (xyz_t* ptr)
{ ... }
int main()
{
xyz_t some_struct =
{
1, // a
2, // b
&func // callback
};
xyz_t another_struct =
{ ... };
some_struct.callback (&another_struct); // calls func
}
缺点是您要键入两次回调类型(当然这不是一个大缺点,但代码重复)。另外,
typedef
ed参数中的struct xyz_*p
不应该是xyz_*p
(因为xyz_*t
已经typedef
ed为一个类型)?@Kninnug是的,关于typedef你是对的,我会更新它。