, :
first_derived_t* object = first_derived_create();
base_some_operation((base_t*) object);
...
C- . C , ++ casts , , - C.
( ?) . -, , C , Base* - . , ++ dynamic_cast, .
( C-, , . , , (Derived1*) derived2_ptr . - - - C-.)
C -
struct base_t_ptr {
void * this_;
};
typedef struct {
struct base_t_ptr get_base;
} derived_t_ptr;
- . , object.get_base :
first_derived_t_ptr object = first_derived_create();
base_some_operation(object.get_base);
base_some_operation
extern "C" base_some_operation(struct base_t_ptr);
This will be completely type safe, as you cannot pass the_1_t_ptr derivative to this function without going through the data element .get_base. It will also help your C code learn a little about types and which conversions are valid - you do not want to accidentally convert Derived1 to Derived2.
Then, when implementing non-virtual methods defined only in a derived class, you will need something like:
extern "C" void derived1_nonvirtual_operation(struct derived1_t_ptr);
void derived1_nonvirtual_operation(struct derived1_t_ptr d) {
Base * bp = reinterpret_cast<Base*>(d.get_base.this_);
Derived1 *this_ = dynamic_cast<Derived1*>;
this_ -> some_operation();
}
source
share