Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C opaque pointer gotchas

I'm working with a legacy C library interface (to C++) that exposes opaque pointers as

typedef void * OpaqueObject

In the library:

OpaqueObject CreateObject()
{
   return new OurCppLibrary::Object();
}

This of course provides absolutely no type safety for clients of this library. Should changing the typedef from a void pointer to structure pointer work exactly the same, but provide a small amount type safety?

typedef struct OpaqueObjectInternal_ *OpaqueObject 
// OpaqueObjectInternal_ is NEVER defined anywhere in client or library code

Are there any alignment issues or other gotchas that I have to worry about now that I am explicitly pointing to a structure, even though I'm really not pointing to one?

like image 413
Cat Zimmermann Avatar asked Dec 27 '22 23:12

Cat Zimmermann


1 Answers

There are no gotcha's; that form is preferred exactly because of type safety.

No, alignment is not an issue here. The pointer itself has a known alignment, and the alignment of the object it will point at is only of concern to the library implementation, not the user.

like image 106
GManNickG Avatar answered Dec 30 '22 13:12

GManNickG