是否可以在运行时更改结构的定义? [英] Is it possible to change the definition of structs at runtime?

查看:44
本文介绍了是否可以在运行时更改结构的定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道你为什么会想要这样做,但我很好奇是否有人知道答案.是否可以在运行时暂时使用一个结构体定义,然后再更改该定义?

I don't know why you would ever want to do this, but I was curious if anyone knew the answer. Is it possible at run time to use one struct definition for a while, and then later change that definition?

typedef struct
{
    int a;
    int b;
}my_struct;

然后……

typedef struct
{
    int a;
    int b;
    int c;
}my_struct;

推荐答案

不,您不能更改给定类型的定义,但是将其强制转换为完全不同的类型并没有错,假设基础数据的布局类似并且兼容.

No, you can't change the definition of a given type, but there's nothing wrong with casting it to a totally different type, assuming the underlying data is similarly laid out and otherwise compatible.

例如,考虑:

struct s_xyzzy {
    int a;
    int b;
};

struct s_plugh {
    int a;
    char b0;
    char b1;
    char b2;
    char b3;
};

struct s_xyzzy *xyzzy = malloc (sizeof (*xyzzy));
((struct s_plugh *)xyzzy)->b0 = 'x';

通过将 xyzzy 转换为不同但兼容的类型,您可以以不同的方式访问字段.

By casting xyzzy to a different but compatible type, you can access the fields in a different way.

请记住兼容性很重要,您必须知道底层内存将在两个结构之间正确对齐.

Keep in mind that compatibility is important and you have to know that the underlying memory will be correctly aligned between the two structures.

您也可以通过使用重叠内存将两个结构放入联合中来实现.

You can also do it by placing both structures into a union, using overlapped memory.

这篇关于是否可以在运行时更改结构的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆