Search code examples
c++vxworkspointer-to-member

Member Function Pointers in VxWorks


I'm writing C++ for a VxWorks application. Since VxWorks is C-based, functions that take functions pointers as arguments are not compatible with C++'s member function pointers.

I have a class (SomeClass) that is instantiated several times with 30+ member functions that I would like to be able to pass to functions like taskSpawn. I know of two ways this can be accomplished, but I'm not particularly fond of either traditional solution:

  1. Use static functions to call a C function pointer on a specific object:

    static void CallFunction1(SomeClass *objectToCallFunction1On);
    static void CallFunction2(SomeClass *objectToCallFunction2On);
    ...
    static void CallFunction30(SomeClass *objectToCallFunction30On);
    
    
    void Function1();
    void Function2();
    ...
    void Function30();
    
  2. Use an integer or enumerated type to specify function to call on a specific object:

    static void CallFunction(SomeClass *objectToCallFunctionOn, int functionToCall);
    
    void Function1();
    void Function2();
    ...
    void Function30();
    

I really, really dislike both of these solutions. Is there a clean, simple solution to this problem?


Solution

  • 1st option is to use an array of function pointers.

    static void (*functionArray[30])(SomeClass *) = {
        Function1,
        Function2,
        Function3,
        Function4
        //
    };
    
    static void CallFunction(SomeClass *objectToCallFunctionOn, int functionToCall) {
       functionArray[functionToCall](objectToCallFunctionOn);
    }
    

    Another option will be to do the same thing with non-type template parameters. But I think the first option solves the issue fairly.