0

私は最近いくつかのコードを見ましたが、特に同様の関数ポインターが明確ではありませんか?

以下は関数ポインタです。

以下の 3 つの関数についても混乱しています。パラメーターの型は「cairo_output_stream_t」ですが、cairo_output_stream_t 構造体には 3 つの関数ポインターのメンバーが含まれています。以下の機能が何をしているのか理解できません。

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 ++のthisポインターをエミュレートするCのような方法です...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);

C++ クラス メソッドがポインターを介してクラス インスタンスの非静的データ メンバーにアクセスできるのと同じ方法で、インスタンスのメンバーにmethod_funcアクセスできるようになりました。datamy_structthis

于 2013-01-31T17:50:12.073 に答える