Representing dynamic typing in C

前端 未结 6 1573
时光说笑
时光说笑 2020-12-14 22:10

I\'m writing a dynamically-typed language. Currently, my objects are represented in this way:

struct Class { struct Class* class; struct Object* (*get)(stru         


        
6条回答
  •  没有蜡笔的小新
    2020-12-14 23:07

    The problem is that, as far as I know, the C standard makes no promises about how structures are stored. On my platform this works. But on another platform struct String might store value before class and when I accessed foo->class in the above I would actually be accessing foo->value, which is obviously bad. Portability is a big goal here.

    I believe you're wrong here. First, because your struct String doesn't have a value member. Second, because I believe C does guarantee the layout in memory of your struct's members. That's why the following are different sizes:

    struct {
        short a;
        char  b;
        char  c;
    }
    
    struct {
        char  a;
        short b;
        char  c;
    }
    

    If C made no guarantees, then compilers would probably optimize both of those to be the same size. But it guarantees the internal layout of your structs, so the natural alignment rules kick in and make the second one larger than the first.

提交回复
热议问题