at_yasu's blog

ロード的なことを

構造体に関数 -- C言語

構造体の要素に関数を指定する方法。

引数と返り値は同じだけど処理が違う場合、配列にして関数を入れて行く。結構便利だけど、文法をよく忘れるのでメモ

まず、それぞれの宣言

// 関数の宣言
unsigned char hiddenType (unsigned char *bitmap, const CGImageAlphaInfo colType);
unsigned char RGBType (unsigned char *bitmap, const CGImageAlphaInfo colType);
unsigned char AlphaType (unsigned char *bitmap, const CGImageAlphaInfo colType);

// 構造体の宣言
struct __fncStr {
    unsigned char (*traceTypes)(unsigned char *bitmap, const CGImageAlphaInfo colType);
};

// 構造体の配列にする。
const static struct __fncStr _traceTypeFnc[] = {
    {.traceTypes=(*hiddenType)},
    {.traceTypes=(*RGBType)},
    {.traceTypes=(*AlphaType)},
    {NULL}
};

後はこんな感じでアクセス

unsigned char type = _traceTypeFnc[type].traceTypes(buff, colorType);