声明相互使用的结构体和函数引用
我需要在旧的 C 中声明一个 (typedef'd) 结构和一个 (typedef'd) 函数引用。这是我的代码:
typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);
typedef struct
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
} monitor_data;
但是它当然不会编译,因为我们不知道函数调用时的结构声明引用。
我已经得到了这个,但它看起来有点乱而且有点难以阅读。
struct _monitor_data;
typedef void (*monitor_calback)(struct _monitor_data*, short int, short int, void*);
typedef struct _monitor_data
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
} monitor_data;
有没有更好的方法来做到这一点?
I need to declare a (typedef'd) structure and a (typedef'd) function reference in pain old C. This is my code:
typedef void (*monitor_calback)(monitor_data*, short int, short int, void*);
typedef struct
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
} monitor_data;
But of course it doen't compile because we don't know about the structure when the function reference is declared.
I have gotten this but it looks kinda messy and is a little hard to read.
struct _monitor_data;
typedef void (*monitor_calback)(struct _monitor_data*, short int, short int, void*);
typedef struct _monitor_data
{
int port;
unsigned char port_state;
monitor_calback cb_high[8];
void *cb_high_data[8];
monitor_calback cb_low[8];
void *cb_low_data[8];
} monitor_data;
Are there any better ways to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在定义结构之前对其进行 typedef:
只要您在完全定义
struct _monitor_data
之前不尝试引用monitor_data
的内部结构,就可以正常工作。对于您的monitor_callback
定义,编译器需要知道的是monitor_data *
是一个指向某个内容的指针,因此只要编译器知道monitor_callback
就可以了monitor_data
存在。这种构造是在 C 中定义不透明类型的标准方法,您只需取消类型的不透明,而不是使其保持不透明。
You can typedef a struct before defining it:
This will work fine as long as you don't try to reference the internal structure of
monitor_data
beforestruct _monitor_data
is fully defined. All the compiler needs to know for yourmonitor_callback
definition is thatmonitor_data *
is a pointer to something somonitor_callback
is fine as long as the compiler knows thatmonitor_data
exists.This sort of construct is the standard approach for defining opaque types in C, you'd just be un-opaquing your type rather than leaving it opaque.
您可以更喜欢以下内容,具体取决于口味:
You could prefer the following, depends on taste tho:
由于
typedef
行为,没有更好的方法。There is no better way because of
typedef
behavior.