A question about exporting a C++ class to C
I've been reading ab开发者_运维知识库out exporting a C++ class so that C can use it. I've followed this good example from Parashift, and a question came out.
To hold the memory allocated to the C++ class, we define the following structure
typedef struct A A;
So that A*
can point to the address of the class A. My question is: does it matter of which type is this pointer? For example, couldn't we typedef something like:
typedef double A;
Since it's probably the C++ code that will be responsible for allocating and deallocating memory.
No, you shouldn't use void*
by this. A pointer to an incomplete type struct A
is a much better technique. This avoids that you mix pointers to different opaque types by accident. If you'd typedef
it to void
you could assign a pointer of your opaque type to any other data pointer. Probably not what you want.
Using an incomplete type gives you a bit of type safety for no cost at all.
Opaque pointers are best declared as void*
.
This is often known as the Pimpl idiom.
You should use the void
type for anything which is intended to be opaque like this. Using a typedef of an undefined struct is ok in that its name can give you a sense of what it really points to.
精彩评论