【问题标题】:Arguments of Function in a C StructureC 结构中的函数参数
【发布时间】:2014-10-23 02:39:58
【问题描述】:

我们有一个结构

typedef struct _disis_thinkgear
{
    t_object x_obj;

    //other members and such

我们需要在结构中有一个成员是一个函数

    void (*handleDataValue)( ????  , unsigned char extendedCodeLevel, 
                               unsigned char code, unsigned char numBytes,
                               const unsigned char *value, void *customData );
} t_disis_thinkgear;

怎么可能???被替换以便 x 是第一个参数?用作

x->handleDataValue =  //another function

【问题讨论】:

    标签: c function pointers struct arguments


    【解决方案1】:

    您需要前向声明 typedef:

    typedef struct _disis_thinkgear t_disis_thinkgear;
    

    那么就可以在结构体的定义中使用类型了:

    struct _disis_thinkgear {
        ...
    
        void (*handleDataValue)(t_disis_thinkgear *x, ...
    };
    

    一旦你得到了这种类型的对象,你可以调用函数:

    t_disis_thinkgear *x = ...
    x->handleDataValue(x, ...);
    

    【讨论】:

    • 你不能在结构里面写void (*handleDataValue)(struct _disis_thinkgear *x, ...这样的东西吗?
    • @AlexReinking 可以,但是前向声明更好,因为这样您就不必在结构中对类型进行特殊使用。
    • @AlexReinking 此外,一些编译器会输出错误消息中写入的类型。让t_disis_thinkgear 出现在错误消息中可能比看到struct _disis_thinkgear 更可取。
    • @JimBalter 有理有据。 +1
    【解决方案2】:

    这是一个有效的完整示例。您实际上可以在结构中使用struct _disis_thinkgear

    #include <stdlib.h>
    #include <stdio.h>
    
    typedef struct _disis_thinkgear {
            // ... other things ...
    
            void (*handleDataValue)(struct _disis_thinkgear *);
    
            // ... other things ...
    } t_disis_thinkgear;
    
    void printSomething(t_disis_thinkgear *foo) {
            printf("argument is %p\n", foo);
    }
    
    int main()
    {
            t_disis_thinkgear *x = malloc(sizeof(x));
            x->handleDataValue = &printSomething;
            x->handleDataValue(x);
            free(x);
            return 0;
    }
    

    【讨论】:

    • 或者你可以将结构体类型定义为部分类型,避免使用不一致:typedef struct _disis_thinkgear t_disis_thinkgear; struct _disis_thinkgear { ... void (*handleDataValue)(t_disis_thinkgear *); ... };
    猜你喜欢
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2021-02-19
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    相关资源
    最近更新 更多