【问题标题】:typedef & function pointertypedef & 函数指针
【发布时间】:2013-01-31 17:46:26
【问题描述】:

最近看到一些代码,特别不清楚类似的函数指针?

以下是函数指针。

我也对下面三个函数感到困惑,参数类型是“cairo_output_stream_t”,但cairo_output_stream_t结构包含三个函数指针的成员。我不明白下面的函数在做什么。

typedef cairo_status_t
(*cairo_output_stream_write_func_t) (cairo_output_stream_t *output_stream,
                                     const unsigned char   *data,
                                     unsigned int           length);

typedef cairo_status_t
(*cairo_output_stream_flush_func_t) (cairo_output_stream_t *output_stream);

typedef cairo_status_t
(*cairo_output_stream_close_func_t) (cairo_output_stream_t *output_stream);

struct _cairo_output_stream {
    cairo_output_stream_write_func_t write_func;
    cairo_output_stream_flush_func_t flush_func;
    cairo_output_stream_close_func_t close_func;
    unsigned long                    position;
    cairo_status_t                   status;
    int                              closed;
};

cairo_status_t 是一个枚举

【问题讨论】:

    标签: c++ typedef


    【解决方案1】:

    基本上正在做的是一种类似 C 的方式来模拟 C++ 的 this 指针...您将指向 struct 的指针作为函数调用的第一个参数传递,然后您可以从该指针调用“方法" 结构(在这种情况下,它们是函数指针)和/或访问结构的数据成员。

    例如,您可能有使用这种编程风格的代码,如下所示:

    struct my_struct
    {
        unsigned char* data;
        void (*method_func)(struct my_struct* this_pointer);
    };
    
    struct my_struct object;
    //... initialize the members of the structure
    
    //make a call using one of the function pointers in the structure, and pass the 
    //address of the structure as an argument to the function so that the function
    //can access the data-members and function pointers in the struct
    object.method_func(&object);
    

    现在method_func 可以访问my_struct 实例的data 成员,就像C++ 类方法可以通过this 指针访问其类实例非静态数据成员一样。

    【讨论】:

    • 我看到一些代码,我很不明白这个表达式“typedef void (*callback)(void);”,你知道我引用的typedef是什么意思吗?
    • 是的。 typedef callback 是一个指向不带参数的函数的指针(即void)并且不返回任何值,因为返回类型是void。顺便说一句,您可能需要确保回调参数类型不是void*,在这种情况下,调用您的回调的函数将向您传递一些数据块。
    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多