Writing a C++ wrapper for a C library

A C++ wrapper is not required - you can simply call the C functions from your C++ code. IMHO, it's best not to wrap C code - if you want to turn it into C++ code - fine, but do a complete re-write.

Practically, assuming your C functions are declared in a file called myfuncs.h then in your C++ code you will want to include them like this:

extern "C" {
   #include "myfuncs.h"
}

in order to give them C linkage when compiled with the C++ compiler.


I usually only write a simple RAII wrapper instead of wrapping each member function:

class Database: boost::noncopyable {
  public:
    Database(): handle(db_construct()) {
        if (!handle) throw std::runtime_error("...");
    }
    ~Database() { db_destruct(handle); }
    operator db_t*() { return handle; }
  private:
    db_t* handle;
};

With the type conversion operator this can be used with the C functions:

Database db;
db_access(db, ...);  // Calling a C function with db's type conversion operator

I think it only makes sense to write a wrapper if it makes the use of the library simpler. In your case, you're making it unnecessary to pass a LIB* around, and presumably it will be possible to create LIB objects on the stack, so I'd say this is an improvement.

Tags:

C++

C

Wrapper