如果使用未命名结构体或未定义标记实现不透明指针

Should an opaque pointer be implemented using an unnamed struct or an undefined tag?

本文关键字:实现 不透明 指针 未定义 未命名 结构体 如果      更新时间:2023-10-16

我目前正在设计一个API,允许用户传递一个不透明的指针,当他必须实现的接口的方法被调用时,他将被传递回来。

这基本上归结为以下内容:

API-side:

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

用户端:

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

UserInterfaceImpl* userInterfaceImpl = new UserInterfaceImpl();
struct UserContext {...} userContext;
SetInterface(userInterfaceImpl, &userContext); // May need a cast

在这种情况下,定义不透明指针的最佳方法是什么?

基本上我想到了typedef struct _CustomContext* CustomContext;它定义了一个指向未定义(正向声明)结构体的指针。

但我也想知道是否typedef struct {} * CustomContext;哪个定义指向未命名结构的指针可能是一个很好的选择?我看到的主要问题是,如果包含在不同的翻译单元中,它可能会定义不同的结构。对吗?

当然,由于类型安全问题,我不想使用void*

如果你要强制强制类型转换,为什么不只是void * ?

但是你只是在这里写C。为什么同时传递接口和上下文——接口的实现是上下文;它是一个对象,有它需要的任何成员变量