简体   繁体   中英

typedef & function pointer

I am recently saw some code, I am especially not clear of similar function pointer?

and below are function pointer.

I also is confused about below three function, the parameter type is "cairo_output_stream_t", but the cairo_output_stream_t structure contain member of there three function pointer. I can not understand what below function are doing.

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 is an enum

What's basically being done is a C-like way to emulate C++'s this pointer ... you pass a pointer to the struct as the first argument to the function call, and from that pointer you can call "methods" of the struct (in this case they are function pointers) and/or access data-members of the struct.

So for instance, you might have code using this style of programming that looks something like the following:

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);

Now method_func can access the data member of the my_struct instance in the same way a C++ class method can access its class-instance non-static data-members through the this pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM