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.