Wrapping C++ in a C Interface

Posted on Sat 22 January 2011 in tech

This is perhaps the simplest, slickest way to wrap C++ in a C interface I've ever seen, courtesy of Matthieu Brucher. The key concept is the forward declaration of the Manager type, which is valid for both C++ and C. Any C that attaches to this interface doesn't have to know that the underlying Manager struct may actually look more like a C++ struct. It just needs a valid pointer to Manager. No need to destroy type information and worry about re-casting void pointers.

First the header file:

#ifndef INTERFACE_H
#define INTERFACE_H

#ifdef __cplusplus
extern "C"
{
#endif

typedef struct Manager Manager;

Manager* create_manager();

void destroy_manager(Manager* manager);

void print_manager(Manager* manager);

#ifdef __cplusplus
}
#endif

#endif

And now the implementation:

#include "interface.h"
#include "manager.h"

Manager* create_manager()
{
    return new Manager;
}

void destroy_manager(Manager* manager)
{
    delete manager;
}

void print_manager(Manager* manager)
{
    manager->print();
}