【问题标题】:Function pointer with struct parameter inside struct结构内带有结构参数的函数指针
【发布时间】:2018-10-24 08:03:55
【问题描述】:

我有一个目前看起来像这样的结构(缩写为仅显示基本部分):

typedef struct {
    uint32_t baudrate;
    ... some other internally used values here
    void (*request_received)(void* hbus); //< this is what I'm talking about
} hbus_options_t;

这行得通。基本上它包含一个函数指针,它接受一个指向 void 类型参数的指针。

我真正想要的是更容易理解:

typedef struct {
    uint32_t baudrate;
    ... some other internally used values here
    void (*request_received)(hbus_options_t* hbus); //< this doesn't work
} hbus_options_t;

显然编译器需要知道该结构,然后我才能使用它。这通常是怎么做的?使用 void 指针有效,但更难理解。

【问题讨论】:

    标签: c function-pointers


    【解决方案1】:

    这是通过不失职并提供结构标签来完成的:

    typedef struct hbus_options {
        uint32_t baudrate;
        ... some other internally used values here
        void (*request_received)(struct hbus_options * hbus); 
    } hbus_options_t;
    

    除了可读性之外,如果您将指针传递给预期结构类型以外的东西,编译器也会报错。

    添加标签还允许组件的松散耦合。可以转发声明结构,但不能声明类型别名。

    【讨论】:

    • 很好的答案,谢谢。是的,我必须对 void* 进行显式强制转换,反之亦然以阻止编译器抱怨。
    • @TomL。 - 您必须将 转换为 void*?这很奇怪。那是一种隐式转换。或者你的意思是你必须转换函数指针?那是有风险的。
    • 我的意思是函数指针,对不起。是的,这就是我不喜欢它的原因。
    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多