Creating a C++/CLI wrapper around a C library

So, following my previous post, I have decided that I might try C++/CLI after all, since the SWIG way goes nowhere except “down in flames”, and I really need to implement it.

Turns out that creating a C++/CLI wrapper around a fairly well-made C library is not that hard.

Considering the following .h file from the C library (which are the methods and structures to interface):

Add the .h and .c files to a new C++ CLR DLL project, then add a new cpp file, in which we will replicate all the C structures as classes.
We have to name our classes differently than the C structures, otherwise there will be conflicts, both with the compiler, and in our heads.

The annoying thing when like me, you know pretty much nothing about C/C++, is that you never know where to specify pointers and stuff, and it’s mostly trial and error (it says it can’t build, let’s add a *… nope, a & ? Yes, that seems to work).

A few things to note:

  • Provide internal ToNative() methods on the structure wrappers to ease up marshalling from managed objects to native structures.
  • Also provide internal constructors taking a native structure as parameter, to ease up marshalling from native to managed.
  • The “^%” syntax (for the “images” parameter of the “Pack” method) builds to a “ref” in the .Net method signature. Otherwise the calling C# can’t get the values back.

As you can see, it’s not that difficult after all. I guess for an experienced C/C++ developer it would be even more simple.