c++ - 不透明指针应该使用未命名的结构还是未定义的标记来实现?

标签 c++ pointers struct opaque-pointers

我目前正在设计一个 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/

相关文章:

c++ - 如何在 POCO C++ 库中正确使用 OpenSSL

c++ - 为什么这个通过宏调用的内联错误函数没有返回到main?

c - 如何使用scanf函数打印字符串的第n项?

c - 当我尝试使用 strncpy 将一个数组缓冲区复制到另一个数组缓冲区时,为什么会出现不兼容的指针类型错误?

c++ - 以支持继承的方式在对象的构造函数中将 shared_ptr 添加到 self to vector

swift - 如何正确打印结构?

c++ - Borland C++,获取小数的问题

c++ - 如何声明一个可以在整个程序中使用的全局 2d 3d 4d ... 数组(堆版本)变量?

c - 从指针到指针的访问值

c++ - 如何将文本文件中的数据读入结构的int数组?