C opaque gotchas pointer

I work with a legacy C library interface (in C ++) that provides opaque pointers like

typedef void * OpaqueObject 

In library:

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

This, of course, is absolutely safe for the clients of this library. Should changing the typedef from the void pointer to the structure pointer work the same way, but provide security in the amount of a small amount?

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

Are there any alignment problems or other errors that I have to worry about now when I explicitly point to the structure, although I really don't point to one?

+4
source share
3 answers

No information; this form is preferred precisely because of type safety.

No, alignment is not a problem here. The pointer itself has a known alignment, and the alignment of the object to which it points is of concern only for the implementation of the library, and not for the user.

+7
source

Actually, the C ++ class is also a C structure. Therefore, you can simply do this:

 struct Object; struct Object* Object_Create(void); 

And, a C wrapper in the library, thus:

 struct Object* Object_Create(void) { return new Object; } 

A method call might look like this:

 uint32_t Object_DoSomething( struct Object* me, char * text ) { return me->DoSomething( text ); } 

I tried this and I see no flaws.

+2
source

The first thing to consider in your course is that you communicate with others who may need to support the code you write. Among other things, opaque objects are way C to tell the library user that the library keeper gives absolutely no guarantee about the implementation of an object other than that the object can be used with documented functions. By removing the void *, you basically declare to the world: "I declare this implementation, which was opaque, to be stable." Perhaps this is not what you want.

Secondly, IMHO, which you offer, is a half solution that does not please anyone; the best approach is to develop a wrapper class. This has the added benefit of allowing you to wrap the init and destroy functions that inevitably accompany opaque C style objects in the constructors and destructors of your class. This will allow you to provide resource management as well as type safety for your customers with much more work.

+1
source

Source: https://habr.com/ru/post/1343688/


All Articles