1

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

这基本上归结为以下几点:

API端:

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*当然,由于类型安全问题,我不想使用 a 。

4

1 回答 1

1

如果你无论如何都要强制转换,为什么不只是void *

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

于 2014-05-07T21:33:34.423 回答