Can we implement ANSI C's `offsetof` in Delphi?

前端 未结 2 1321
忘掉有多难
忘掉有多难 2020-12-10 18:21

For reference: The offsetof macro(!) takes a struct data type and a member of the specified struct as arguments and returns an integer offset of th

相关标签:
2条回答
  • 2020-12-10 18:50

    Without a pre-processor or a built-in function, there's no way to do it quite as cleanly as the offsetof macro. The way that offsetof is able to do it so cleanly is that the pre-processor does the work. In fact some compilers implement it as a built-in, but that's beside the point. Delphi has no pre-processor, and no built-in offsetof.

    The cleanest solution I know is like this:

    NativeUInt(@TMyRecord(nil^).MyField)
    

    But that is nothing like as clean as

    offsetof(struct MyStruct, MyField)
    
    0 讨论(0)
  • 2020-12-10 19:13

    To expand on @DavidHeffernan's answer and @UliGerhardt's comment, here's what we now use, tested and in use:

    procedure foo;
    type
      TPerson = record
        DOB: TDate;
        FirstName: string;
        LastName: string;
      end;
    const
      Offset_TPerson: ^TPerson = nil;
    begin
      writeln('OffsetOf FirstName = '+IntToStr(NativeUInt(@Offset_TPerson.FirstName)));
    end;
    
    0 讨论(0)
提交回复
热议问题