2013-01-31 239 views
0

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

以下是函数指针。

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

+0

严......什么? – 2013-12-10 10:57:04

回答

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可以以同样的方式访问my_struct实例的data成员C++类方法:

因此,举例来说,你可以使用这种编程风格,看起来像下面有代码可以通过this指针访问其类实例非静态数据成员。

+0

我看到一些代码,我很不理解这个表达式“typedef void(* callback)(void);”,你知道我引用的typedef的含义是什么意思吗? – user1279988

+0

是的。 typedef'callback'是一个函数的指针,它不带任何参数(即它是'void'),并且返回没有值,因为返回类型是'void'。顺便说一句,你可能想要确保回调参数类型不是'void *',在这种情况下,调用回调函数会传递给你一些数据块。 – Jason