11 years, 10 months ago.

How to wrap C functions into C++ class?

Hi all,

I'm wrapping some C functions into a C++ class, like mbed library. All functions in C are global functions, so should this class be a singleton, or could be a normal class? Even the functions are handling hardware? BTW, do you have any suggestion on how to wrap a C library into a C++ library?

Thanks a lot!

Why do you feel you have to do it? Why not just call C functions as-is?

posted by Igor Skochinsky 09 Jan 2013

I think it will be easier for other people to use the classes. Like the mbed library.

posted by Ye Cheng 09 Jan 2013

1 Answer

11 years, 10 months ago.

Hi Ye, In the mbed library we usually avoid wrapping C functions.

Two examples of that are:

As you can see, the only convention that you have to follow is declaring their prototype as extern "C" if the file is compiled as C++:

#ifdef __cplusplus
extern "C" {
#endif
 
[...] // Your prototypes here
 
#ifdef __cplusplus
}
#endif

As discussed in another question there are small exceptions, if we think that a set of functions could become an object in the future.

In the mbed library we provide C++ wrappers for C objects.

By C object, I mean a C structure and a set of functions that take a reference to an instance of that structure as one of the parameters.

As an example take the GPIO C object for the LPC1768:

typedef struct {
    PinName  pin;
    uint32_t mask;
    
    __IO uint32_t *reg_dir;
    __IO uint32_t *reg_set;
    __IO uint32_t *reg_clr;
    __I  uint32_t *reg_in;
} gpio_t;

void gpio_init(gpio_t *obj, PinName pin, PinDirection direction);

void gpio_write(gpio_t *obj, int value);
 
int gpio_read(gpio_t *obj);

This gets wrapped in a C++ class like this:

class DigitalOut {

public:
    DigitalOut(PinName pin) {
        gpio_init(&gpio, pin, PIN_OUTPUT);
    }
    
    void write(int value) {
        gpio_write(&gpio, value);
    }
    
    int read() {
        return gpio_read(&gpio);
    }

protected:
    gpio_t gpio;
};

HTH, Emilio

Accepted Answer

Thank you very much Emilio! I'm clear now.

posted by Ye Cheng 09 Jan 2013