【发布时间】: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