【问题标题】:Offset of record field as constant记录字段的偏移量为常数
【发布时间】:2018-04-19 07:23:24
【问题描述】:

我正在使用如下技术在运行时获取记录字段的偏移量:

procedure DoSomethingWithVar(var AField);
DoSomethingWithVar(TGUID(nil^).D3); // TGUID and D3 for exposition only :-)

这很好用。现在我想将这些偏移量设为consts,但无法正常工作:

const
  cMyVarTyped: Pointer = @TGUID(nil^).D3;
  cMyVarUntyped = @TGUID(nil^).D3;
  cMyOffsetTyped: INT_PTR = INT_PTR(@TGUID(nil^).D3);
  cMyOffsetUntyped = INT_PTR(@TGUID(nil^).D3);

所有这些都会产生“E2026 Constant expression expected”。有什么想法吗?

FWIW:将声明包装在 {$WRITEABLECONST ON}/{$WRITEABLECONST OFF} 中不会改变错误。

【问题讨论】:

  • 也许你可以在运行时使用Writeable typed constants 做一些事情
  • @RemyLebeau 偏移常量将是 const array[TSomeEnum] of TSomeRecord 的一部分。我已经考虑将其设为var,但更愿意保留常量。
  • idea with writable constant 还不错(当然是以可写常量为代价)。
  • 因为我需要一个 array of record 我已经有一个类型化的 const,所以我通过使用可写的 const 或 var 所释放的只是编译时 const 的正确性。无论如何,这将是一个半丑陋的妥协,所以我将继续使用我当前的解决方案,它是一个由 case TSomeEnum of 组成的函数 GetOffset。
  • "在 {$WRITEABLECONST ON} 中包装声明不会改变错误" - 我并不是说它会神奇地使声明在编译时工作.通过使常量可写,您可以在运行时动态分配它们,例如在initialization 块中。你试过吗? const {$J+} cMyVarTyped: Pointer = nil; ... initialization cMyVarTyped := @TGUID(nil^).D3;

标签: delphi constants offset record


【解决方案1】:

不可能让编译器生成一个包含成员偏移量的常量表达式。

【讨论】:

    猜你喜欢
    • 2013-01-05
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2020-04-10
    • 1970-01-01
    相关资源
    最近更新 更多