How to simulate bit-fields in Delphi records?

前端 未结 4 2059
终归单人心
终归单人心 2020-12-04 18:32

I would like to declare a record in Delphi that contains the same layout as it has in C.

For those interested : This record is part of a union in the Windows OS\'s L

4条回答
  •  醉梦人生
    2020-12-04 19:03

    Well, you basically need to get down to the dirty with bit-manipulation.

    Why, specifically, do you need to retain that structure?

    If you only need to talk to a legacy program that either talks in this dialect (TCP/IP or similar), or stores data in this manner (files, etc.), then I would map a normal Delphi structure to a bit-version compatible. In other words, I would use a normally structured Delphi structure in memory, and write code to write and read that structure in a compatible manner.

    If you need to save memory, I would make getters and setters that manipulate bits of internal integers or similar. This will have a performance impact, but not much more than what the original C program would have, the only difference is that the bit-manipulation would be added by compiler magic in the C version, whereas you will have to write it yourself.

    If you don't have many records in memory, and don't need to talk to another program, I'd use a natural Delphi structure. Trade-off for higher performance will be more memory used.

    But it all depends on your criteria.

    In any case, you won't be able to talk the Delphi compiler into doing the same job for you as the C compiler.

    PACKED RECORD, suggested by another here, doesn't do that, and was never meant to. It will only remove alignment padding to put integers on 32-bit boundaries and similar, but won't pack multiple fields into one byte.

    Note that a common way to do this is through Delphi SETS, which are implementing internally using bit-fields. Again, you will have different code than the C variant.

提交回复
热议问题