我目前正在设计一个 API,允许用户传递一个不透明的指针,稍后当他必须实现的接口(interface)方法被调用时,他将被传回。
这基本上可以归结为以下几点:
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*
。
最佳答案
如果无论如何都要强制转换,为什么不只是 void *
?
但是你只是在这里写 C。为什么要同时传递接口(interface)和上下文——接口(interface)的实现就是上下文;它是一个对象,具有它需要的任何成员变量。
关于c++ - 不透明指针应该使用未命名的结构还是未定义的标记来实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23528573/