Is it possible to change the definition of structs at runtime? [closed]

前提是你 提交于 2019-12-10 12:04:38

问题


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?

i.e.

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

and later on...

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

回答1:


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.

For example, consider:

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';

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.




回答2:


If you're talking about runtime polymorphism, then it can be made to work, but you have to know what you're doing. Read ooc.pdf by Axel Schreiner.



来源:https://stackoverflow.com/questions/16117154/is-it-possible-to-change-the-definition-of-structs-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!