Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

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

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 the given member relative to the beginning of the struct. See the detailed overview and references.

The logic behind the generic offsetof is quite simple and can be reproduced in Delphi with ease (more or less) (literally with ease, elimination of predeclared pointer type requirement makes it a basic inline expression, see David Heffernan's answer and comment about swapping reference and dereference operators) as in-place code. However, I see absolutely no way to convert the in-place code solution to the reusable function. Can we actually do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...