【发布时间】:2020-12-14 22:02:33
【问题描述】:
我正在为一个 c++ 库开发一个 c-api 包装器。我也是c++库的维护者。
到目前为止,我的基本策略是为库中的每个 c++ 类设置一个不透明的句柄。 我将句柄声明为结构:
struct Handle_;
typedef struct Handle_ *Handle;
然后在我的 c-api 包装头中,我为类的每个成员函数都有一个函数,包括创建和销毁。我已经按照这篇文章中的描述实现了它: https://stackoverflow.com/a/2045860/3237961
但知道我有以下问题:
注意:要重现问题,不需要 c-api 包装器。这都是关于铸造的。
假设我有一个继承自两个抽象类(即接口)的类:
class T_IDeviceInfo {
public:
virtual int getDeviceType() = 0;
};
class T_IDeviceControl {
public:
virtual void open() = 0;
};
class T_Device : public T_IDeviceInfo, public T_IDeviceControl {
public:
int getDeviceType() override {
std::cout << "T_Device::getDeviceType()" << std::endl;
return 0;
}
void open() override {
std::cout << "T_Device::open()" << std::endl;
}
};
在下面的代码中,我使用了上面声明的类:
int main(){
//Prints the device type message and the open message from T_Device
T_Device* device = new T_Device();
device->getDeviceType();
device->open();
//works
std::cout << "cast as derived class" << std::endl;
reinterpret_cast<T_IDeviceInfo*>(device)->getDeviceType();
reinterpret_cast<T_IDeviceControl*>(device)->open();
std::cout << std::endl;
void* handle = reinterpret_cast<void*>(device);
//works
std::cout << "cast handle as derived class" << std::endl;
reinterpret_cast<T_Device*>(handle)->getDeviceType();
reinterpret_cast<T_Device*>(handle)->open();
//does not work
std::cout << "cast handle as base class (i.e. interface)" << std::endl;
reinterpret_cast<T_IDeviceInfo*>(handle)->getDeviceType();
reinterpret_cast<T_IDeviceControl*>(handle)->open();
}
输出如下所示:
T_Device::getDeviceType()
T_Device::open()
cast as derived class
T_Device::getDeviceType()
T_Device::open()
T_Device::getDeviceType()
T_Device::open()
cast handle as derived class
T_Device::getDeviceType()
T_Device::open()
cast handle as base class (i.e. interface)
T_Device::getDeviceType()
T_Device::getDeviceType()
所以问题是最后一节。当我将我的通用句柄转换为基类(接口)时,它的函数被声明了。似乎它总是调用继承顺序第一个的类的函数。 到目前为止,我所读到的是,演员现在不关心班级规模并计算错误的偏移量。它是否正确?你能帮我澄清一下吗?
我做了一些研究并注意到以下几点:
当使用static_cast<>() 而不是reinterpret_cast<>() 时,我得到了相同的输出。
我知道使用不同的铸造方法会有所不同,但我很困惑哪种方法最适合我的任务。
所有关于 c wrapper api 的帖子都提出了上述链接答案中的方法,并使用 reinterpret_cast 或 static_cast。
是否可以将通用句柄转换为派生类的基类。这会为我节省很多工作,因为接口用于不同的设备类,所以我不需要为每个设备重写 c 包装函数。
感谢任何帮助。 谢谢!
【问题讨论】:
标签: c++ inheritance casting wrapper