Representing dynamic typing in C

前端 未结 6 1558
时光说笑
时光说笑 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:50

    Section 6.2.5 of ISO 9899:1999 (the C99 standard) says:

    A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

    Section 6.7.2.1 also says:

    As discussed in 6.2.5, a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence, and a union is a type consisting of a sequence of members whose storage overlap.

    [...]

    Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

    This guarantees what you need.

    In the question you say:

    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.

    This will work on all platforms. It also means that your first alternative - what you are currently using - is safe enough.

    But on another platform struct StringInteger 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.

    No compliant compiler is allowed to do that. [I replaced String by Integer assuming you were referring to the first set of declarations. On closer examination, you might have been referring to the structure with an embedded union. The compiler still isn't allowed to reorder class and value.]

提交回复
热议问题