How can I implement a dynamic dispatch table in C

前端 未结 3 2074
春和景丽
春和景丽 2020-12-01 22:11

First of all, I understand how to implement a dispatch table using function pointers and a string or other lookup, that\'s not the challenge.

What I\'m looking for i

3条回答
  •  生来不讨喜
    2020-12-01 22:35

    As your Strategy.c obviously already knows about the strategy instances by name ("#include "XYstrategy.h") you could go the whole mile and use the header files instead of the implementation files to communicate your strategy to the central dispatcher:

    MyFirstStrategy.h

    #include "Strategy.h"
    void firstStrategy( int param );
    #define MY_FIRST_STRATEGY {"First Strategy", firstStrategy}
    

    MyOtherStrategy.h

    #include "Strategy.h"
    void otherStrategy( int param );
    #define MY_OTHER_STRATEGY {"Other Strategy", otherStrategy }
    

    Strategy.c

    #include "Strategy.h"
    #include "MyFirstStrategy.h"
    #include "MyOtherStrategy.h"
    
    dispatchTableEntry_t dispatchTable[] = {
        MY_FIRST_STRATEGY,
        MY_OTHER_STRATEGY
    };
    int numStrategies = sizeof( dispatchTable ) / sizeof(dispatchTable[0] );
    

    This should work on any C compiler and platform without any link-time tricks.

提交回复
热议问题