Representing dynamic typing in C

前端 未结 6 1555
时光说笑
时光说笑 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 22:52

    C gives you sufficient guarantees that your first approach will work. The only modification you need to make is that in order to make the pointer aliasing OK, you must have a union in scope that contains all of the structs that you are casting between:

    union allow_aliasing {
        struct Class class;
        struct Object object;
        struct Integer integer;
        struct String string;
    };
    

    (You don't need to ever use the union for anything - it just has to be in scope)

    I believe the relevant part of the standard is this:

    [#5] With one exception, if the value of a member of a union object is used when the most recent store to the object was to a different member, the behavior is implementation-defined. One special guarantee is made in order to simplify the use of unions: If a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

    (This doesn't directly say it's OK, but I believe that it does guarantee that if two structs have a common intial sequence and are put into a union together, they'll be laid out in memory the same way - it's certainly been idiomatic C for a long time to assume this, anyway).

提交回复
热议问题