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

查看:198
本文介绍了我们可以在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中轻松复制(或多或少)(从字面上来说,消除predeclared指针类型要求使其成为基本的内联表达式,请参阅David Heffernan的回答引用和取消引用运算符的注释)作为就地代码,可以使用.com / questions / 18786986 / can-we-implement-ansi-cs-offsetof-in-delphi#comment27701712_18787282。但是,我绝对没有办法将就地代码解决方案转换为可重用功能。我们可以这样做吗?

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天全站免登陆