0

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

以下是函数指针。

我也对以下三个函数感到困惑,参数类型是“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 是一个枚举

4

1 回答 1

3

基本上正在做的是一种类似 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可以访问实例的data成员,就像 C++ 类方法可以通过指针my_struct访问其类实例非静态数据成员一样。this

于 2013-01-31T17:50:12.073 回答