将类对象强制转换为结构对象 C/C++ [英] cast class object to struct object C/C++
问题描述
我有两个项目,一个在 C 中,另一个在 C++ 中,我尝试将 C++ 中的类对象转换为 C 中的结构对象.例如,我有一个来自 myClass 的对象,我试图将其转换为 myStru如下:
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:
在我的 C++ 项目中,我有这个类:
In my C++ project I have this class:
class myClass{
myClass();
~myClass();
char *data;
int var;
}
在我的 C 项目中,我有这样的结构:
In my C project I have this structure:
struct myStru {
char *data;
int var;
};
typedef struct myStru myStru;
现在在我的 C++ 项目中,我从 myClass
创建一个对象:
Now in my C++ project I create an object from myClass
:
myClass *classObj = new myClass();
classObj->data = new char[10];
classObj->var = 99;
在我的 C 项目中,我将 classObj
作为空指针接收,并尝试将其转换如下:
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
我稍后会在我的 C++ 项目中这样做
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;
我在这里做的对吗?即,以这种方式将 classObj
转换为 struObj
?
Is what I'm doing here right? i.e., casting classObj
to struObj
in that way?
完整的例子可以在这里找到(感谢@Borgleader)http://coliru.stacked-crooked.com/a/05543b944ee23f2f
The full example can be found here (thanks @Borgleader) http://coliru.stacked-crooked.com/a/05543b944ee23f2f
我在这篇文章中找到了一个很好的答案(请参阅从 C 访问 C++ 类):https://www.oracle.com/technical-resources/articles/it-infrastructure/mixing-c-and-cplusplus.html
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
推荐答案
我不是 100% 肯定,因为它是 C++,你永远不可能,但我认为这是未定义的行为.
I am not 100% sure, because it's C++ and you can never be, but I think this is undefined behaviour.
您不能通过指向另一个结构的成员的指针访问结构的成员.该规则的一个显着例外涉及访问作为联合成员的两个结构的公共初始序列.
You cannot access the members of a struct via a pointer to a member to another struct. A notable exception of that rule involves accessing the common initial sequence of two structs that are members of a union.
如果您实际上是从结构中继承了您的类,这可能会起作用.
This could work if you actually inherited your class from the struct instead.
或者,另一个例外是您可以安全地在此类结构之间memcpy
,AFAIR.
Alternatively, the other exception is that you can safely memcpy
between such structs, AFAIR.
这篇关于将类对象强制转换为结构对象 C/C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!