0

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

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see some code, and I am very not understand this expression"typedef void (*callback)(void);", do you know what meaning of my quoted typedef mean?
Yes. The typedef callback is a pointer to a function that takes no arguments (i.e., it's void) and returns no values since the return type is void. BTW, you may want to make sure the callback argument type wasn't a void*, in which case the function that calls your callback will pass you some block of data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.