I have two projects one in C and the other in C++ and I try to cast a class object in C++ to a structure object in C. For example, I have an object from myClass which I'm trying to cast to myStru as follows:
In my C++ project I have this class:
class myClass{
myClass();
~myClass();
char *data;
int var;
}
In my C project I have this structure:
struct myStru {
char *data;
int var;
};
typedef struct myStru myStru;
Now in my C++ project I create an object from myClass
:
myClass *classObj = new myClass();
classObj->data = new char[10];
classObj->var = 99;
In my C project I receive classObj
as a void pointer and I try to cast it as follows:
myStru *struObj = (myStru*)malloc(sizeof(struct myStru));
struObj = (myStru*) classObj;
printf(" struObj->var %d \n", struObj->var); // this print 99
I do this later in my C++ project
delete []classObj->data; // I know smart pointers can be used here but this is not my point in this question now
delete classObj;
Is what I'm doing here right? i.e., casting classObj
to struObj
in that way?
The full example can be found here (thanks @Borgleader) http://coliru.stacked-crooked.com/a/05543b944ee23f2f
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