Monday, February 08, 2010

Function pointers

Here is an example, we have a structure named Slice, the function like ‘get_direct_motion_vectors’ should really be put inside this structure. So we can use ‘Slice->get_direct_motion_vectors(…)’instead of just call that function. So put a function pointer inside the structure is a good one:
typedef struct slice
{
    int picture_id;
    void (*get_direct_motion_vectors)    (Macroblock *currMB);
    ...
}Slice;

// Usage: 

(*currSlice)->get_direct_motion_vector = Get_MV;

// where ‘Get_MV’ is defined in another .h file: mv_search.h
extern void Get_MV(Macroblock *currMB);

// and it is implemented in .c file: mv_search.c
void Get_MV(Macroblock *currMB) { . . .}

[update 2/19/2012] Garmin asked
The function pointer inside the structure make C look like Object Oriented.
Because C does not support classes, structs are used.
Because structs do not support methods, function pointers are used
Comparing Objects: C++ /C:

class algo{
public:
// methods
   int method1(int param);
   int method2(int param);
// attributes
   int attr1;
   int attr2;
}

typedef struct {
// methods
   int (*method1) (int param);
   int (*method2) (int param);
// attributes
   int attr1;
   int attr2;
} algo;

No comments:

Post a Comment