将一个结构指针投射到另一个-C [英] Casting one struct pointer to another - C
问题描述
请考虑以下代码。
enum type {CONS, ATOM, FUNC, LAMBDA};
typedef struct{
enum type type;
} object;
typedef struct {
enum type type;
object *car;
object *cdr;
} cons_object;
object *cons (object *first, object *second) {
cons_object *ptr = (cons_object *) malloc (sizeof (cons_object));
ptr->type = CONS;
ptr->car = first;
ptr->cdr = second;
return (object *) ptr;
}
在缺点
函数,变量 ptr
的类型为 cons_object *
。但是在返回值中,它将转换为 object *
的类型。
In the cons
function, variable ptr
is of type cons_object*
. But in the return value it is converted to type of object*
.
- 我想知道这怎么可能,因为
cons_object
和object
是不同的结构。 - 做这样的事情有什么问题吗?
- I am wondering how this is possible because
cons_object
andobject
are different structs. - Are there any issues in doing stuff like this?
任何想法!
推荐答案
这很好,是在C中实现面向对象的相当普遍的技术。因为<$ c $的内存布局c> struct s在C中定义明确,只要两个对象共享相同的布局,则可以安全地在它们之间强制转换指针。也就是说, type
成员的偏移量在 object
结构中与在<$ c中相同$ c> cons_object 结构。
This is fine and is a fairly common technique for implementing "object-orientation" in C. Because the memory layout of struct
s is well-defined in C, as long as the two object share the same layout then you can safely cast pointers between them. That is, the offset of the type
member is the same in the object
struct as it is in the cons_object
struct.
在这种情况下, type
成员告诉API,无论 object
是 cons_object
还是 foo_object
或其他
In this case, the type
member tells the API whether the object
is a cons_object
or foo_object
or some other kind of object, so you might be see something like this:
void traverse(object *obj)
{
if (obj->type == CONS) {
cons_object *cons = (cons_object *)obj;
traverse(cons->car);
traverse(cons->cdr);
} else if (obj->type == FOO) {
foo_object *foo = (foo_object *)obj;
traverse_foo(foo);
} else ... etc
}
更常见的是似乎将父类定义为子类的第一个成员的实现,例如:
More commonly, I've seem implementations where the "parent" class is defined as the first member of the "child" class, like so:
typedef struct {
enum type type;
} object;
typedef struct {
object parent;
object *car;
object *cdr;
} cons_object;
此方法的工作方式大致相同,不同之处在于您有很强的保证孩子的班级将与父母相同。也就是说,如果将成员添加到基础 对象
,子代会自动选择该成员,而无需手动确保所有这些结构是同步的。
This works in largely the same way, except you've got a strong gaurantee that the memory layout of the child "classes" will be the same as the parents. That is, if you add a member to the 'base' object
, it'll automatically be picked up by the children and you won't have to manually make sure all of the structures are in sync.
这篇关于将一个结构指针投射到另一个-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!