简体   繁体   中英

Storing function pointer from constructor to private variable

I'm attempting to develop an embedded library for microcontrollers in a (potentially futile) attempt at being device-generic. Essentially, I have a struct declared in the header, called CallbackStruct , that has a whole bunch of function pointers for downstream control of a UART object (ie the Serial object of Arduinos, just to point out one potential usage).

The issue is that I'm not quite sure how to assign one function pointer (especially when dereferenced from a struct) to another that is stored as a private variable. Essentially, I need an understanding of the proper C++ syntax for function pointers. Here's what I have so far:

The header:

class SomeUARTDevice {
public:
    struct CallbackStruct {
        void    (*init) (int);
        void    (*xmit) (char *);
        int     (*recv) (void);
        int     (*avbl) (void);
        void    (*flsh) (void);
        void    (*kill) (void);
    };

    SomeUARTDevice (struct CallbackStruct *sc);

private:
    void    (*init_callback)    (int);
    void    (*xmit_callback)    (char *);
    int     (*recv_callback)    (void);
    int     (*avbl_callback)    (void);
    void    (*flsh_callback)    (void);
    void    (*kill_callback)    (void);
}

And, then in the class source:

SomeUARTDevice::SomeUARTDevice (struct CallbackStruct *sc) {
    init_callback = sc->init;
}

Is this the proper way to assign the function pointer (and if not, how far am I off - by a little bit, or by a mile)?

Note that if there happen to be other syntactical boo-boos, I quickly threw this together as an example to demonstrate the issue without the clutter of the main work-in-progress.

That looks fine. Function pointers work pretty much just like any other pointer.

But note that you could initialize your members directly, using the constructor's initializer list:

SomeUARTDevice::SomeUARTDevice(const CallbackStruct *sc)
    : init_callback(sc->init)
    , xmit_callback(sc->xmit)
    // etc
{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM