1

I am currently designing an API that allows the user to pass an opaque pointer that he will be passed back later on when the methods of an interface he has to implement are called.

This basically goes down to the following:

API-side:

class IAPIInterface
{
  public:
    virtual void APIMethod(CustomContext ctx) = 0;
}

void SetInterface(IAPIInterface* api, CustomContext ctx);

User-side:

class UserInterfaceImpl : public IAPIInterface
{
  public:
    virtual void APIMethod(CustomContext ctx) {...}
};


UserInterfaceImpl* userInterfaceImpl = new UserInterfaceImpl();

struct UserContext {...} userContext;

SetInterface(userInterfaceImpl, &userContext); // May need a cast

What is the best way to define an opaque pointer in that scenario ?

Basically I thought of typedef struct _CustomContext* CustomContext; which defines a pointer to an undefined (forward declared) struct.

But I was also wondering whether typedef struct {} * CustomContext; which define a pointer to an unnamed struct could be a good alternative? The main problem I see is that maybe it will defines different struct if included in different translation unit. It that correct?

Of course I don't want to use a void* because of type safety issue.

HiroshimaCC
  • 486
  • 4
  • 11

1 Answers1

1

If you're going to force casts anyway, why not just void *?

But you're just writing C here. Why pass both an interface and a context - the implementation of the interface is the context; it's an object, with whatever member variables it needs.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • 1) Because `void*` provides no type safety ; anything can be cast to `void*` without consent. Requiring an explicit cast is better, the intention of the user should be obvious. 2) I over simplified my example, but it's not C, it's (meant to be) C++. The main point of the question is the technical/semantical difference between a `typedef'ed undefined structure pointer` and a `typedef'ed unnamed structure pointer`. – HiroshimaCC May 08 '14 at 15:12