typedef & function pointer

typedef & function pointer

本文关键字:pointer function typedef      更新时间:2023-10-16

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

下面是函数指针。

我也对下面的三个函数感到困惑,参数类型是"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 的方式来模拟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指针访问其类实例非静态数据成员一样。