Is possible to cast between C++ class
and C structure
? (the use case here is that I have two different projects one in C++
and the other is in C
and I have an interface to connect both projects)
I have tried some examples where both (a C++ class
and a C structure
) have the same member functions and member variables and this worked fine. But once there is a missing member function/variable in any of them that does not work and casting doesn't give the right values for the member variables.
One thing I've noticed is that if I add a destructor to the C++ class
this would work fine as far as the destructor is not defined virtual
?
In C++
:
class myClass{
public:
myClass() {}
~myClass(){} // if I define this destructor as virtual the casting fails
int var;
};
In C
:
struct myStru {
int var;
};
Casting in C
myStru *struObj = (myStru*)malloc(sizeof( myStru));
struObj = (myStru*) classObj; // classObj is a void pointer that is passed to the `C` project and it was created in the `C++` project
EDIT: I found a good answer to my question in this article (see Accessing C++ Classes from C): https://www.oracle.com/technical-resources/articles/it-infrastructure/mixing-c-and-cplusplus.html