我将一个简单的 C++ 继承层次结构包装到“面向对象”的 C 中。我试图弄清楚在将指向 C++ 对象的指针视为指向不透明 C 结构的指针时是否存在任何问题。特别是,在什么情况下派生到基的转换会引起问题?
类本身相对复杂,但层次结构较浅,仅使用单继承:
// A base class with lots of important shared functionality
class Base {
public:
virtual void someOperation();
// More operations...
private:
// Data...
};
// One of several derived classes
class FirstDerived: public Base {
public:
virtual void someOperation();
// More operations...
private:
// More data...
};
// More derived classes of Base..
我计划通过以下相当标准的面向对象的 C 将其公开给 C 客户端:
// An opaque pointers to the types
typedef struct base_t base_t;
typedef struct first_derived_t first_derived_t;
void base_some_operation(base_t* object) {
Base* base = (Base*) object;
base->someOperation();
}
first_derived_t* first_derived_create() {
return (first_derived_t*) new FirstDerived();
}
void first_derived_destroy(first_derived_t* object) {
FirstDerived* firstDerived = (FirstDerived*) object;
delete firstDerived;
}
C 客户端只传递指向底层 C++ 对象的指针,并且只能通过函数调用来操作它们。所以客户端最终可以做类似的事情:
first_derived_t* object = first_derived_create();
base_some_operation((base_t*) object); // Note the derived-to-base cast here
...
并使对 FirstDerived::someOperation() 的虚拟调用按预期成功。
这些类不是标准布局,但不使用多重继承或虚拟继承。这能保证工作吗?
请注意,如果重要的话,我可以控制所有代码(C++ 和 C 包装器)。