What is the correct typedef for an opaque C pointer to a C++ class?

  • A+
Category:Languages

There are dozens upon dozens of SO questions and blog posts that describe wrapping a C++ class with a C API. Example Wrapping C++ class API for C consumption

Most of these answers and blogposts go for something like this:

typedef void* CMyClass; 

But others say that this is bad because it provides no type safety. They propose various variations of opaque structs, without any explanation. I could just copy the above snippet and move on with my life (which I will do in the meantime), but I'd like to know once and for all

  • Which form is the best?
  • Which guarantees does it provide over void*?
  • How does it work?

 


Use struct MyType in C++.

Use typedef struct MyType* pMyType; as your common handle.

Your "C" APIs should compile in both C and C++ (with extern "C" wrappers in C++ to get correct linkage). And you'll get close to max type safety.

Now, struct MyHandle{void* private_ptr;}; is another option: this avoids exposing the name of the C++ type to C. And so long as you isolate direct interaction with private_ptr to a handful of functions, it will be as type safe everywhere else.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: