Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a c wrapper for C++ library

Tags:

c++

c

abi

api

Is wrapping a c++ library to C via opaque pointers gives a stable ABI interface ? I am clear about ABI interface and why c++ is not having a stable one. This has to do with name mangling and lot other stuff. I know C is very stable in that part. It is also easy to wrap a C library into various other languages compared to C++. These two are driving force to make a c API for my library.

When wrapping a C++ library to C the underlying code is still C++. I my case it is c++ with boost shared ptr and other dependencies.

So since the underlying code is in C++, how the ABI stability is achieved. Or in other words, there is still c++ stuff compiled in the shared library (.so, .dll etc..)

I would like to know how it works. Perhaps someone can provide me with an example that very well explains this stuff.

like image 413
rkm Avatar asked Feb 25 '16 09:02

rkm


1 Answers

Yes, you can create a stable C-Inteface for a C++ implementation. Of course, the C-Interface only offers C-features. Still it can be handy to use C++ for the actual implementation. Here an example where you have a single C++ implementation with function templates and you offer for some variants a C-Interface:

// Internal C++ implementation
template <typename T>
void
foo(T &a, const T &b)
{
    // do something
}


// C Interface
extern "C" {

void
sfoo(float *a, const float *b)
{
    foo(*a, *b);
}

void
dfoo(double *a, const double *b)
{
    foo(*a, *b);
}

} // extern "C"

So basically the compiler will generate different implementations for T=float and T=double:

  • Of course you don't have function overloading. So you have to do the name mangling handish. E.g. sfoo for float, dfoo for double, ... (You also can do this using the pre-processor in C. But it is not that nice to read and maintain.)
  • You don't have references. So instead of references the interface exposes non-const pointers.
like image 83
Michael Lehn Avatar answered Sep 30 '22 11:09

Michael Lehn