我们可以在 Delphi 中实现 ANSI C 的 `offsetof` 吗? [英] Can we implement ANSI C's `offsetof` in Delphi?

查看:24
本文介绍了我们可以在 Delphi 中实现 ANSI C 的 `offsetof` 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

供参考:offsetof 宏(!) 将struct 数据类型和指定结构的成员作为参数,并返回给定成员相对的整数偏移量到结构的开头.请参阅详细概述和参考资料.

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.

泛型 offsetof 背后的逻辑非常简单,可以在 Delphi 中轻松重现 (或多或少)(字面上轻松,消除了预先声明的指针类型要求使其成为基本的内联表达式,请参阅 David Heffernan 的 answer关于交换引用和取消引用运算符的评论)作为就地代码.但是,我认为绝对没有办法将就地代码解决方案转换为可重用功能.我们真的能做到吗?

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?

推荐答案

如果没有预处理器或内置函数,就没有办法像 offsetof 宏那样干净利落地做到这一点.offsetof 能够如此干净地做到这一点的方式是预处理器完成工作.事实上,一些编译器将它实现为内置的,但这不是重点.Delphi 没有预处理器,也没有内置的 offsetof.

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)

但这一点也不像

offsetof(struct MyStruct, MyField)

这篇关于我们可以在 Delphi 中实现 ANSI C 的 `offsetof` 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆