How to write Delphi compile-time functions

江枫思渺然 提交于 2019-12-10 05:30:45

问题


Delphi - can I write my own compile-time functions for const and var declarations, executable at compiler time.

Standard Delphi lib contain routines like Ord(), Chr(), Trunc(), Round(), High() etc, used for constant initialization.

Can I write my own, to execute routine at compile-time and use the result as constant?


回答1:


You cannot write your own intrinsic functions. Because that requires compiler magic.
However there may be other options to achieve your goal.

Preprocessor
The only way is to use a preprocessor.
There are several: http://wiki.delphi-jedi.org/wiki/JEDI_Pre_Processor

The Delphi preprocessor http://sourceforge.net/p/dpp32/wiki/Home/history

Andreas Hausladen has just open sourced his own work in this respect.
It's not really a preprocessor, but a language extender.
https://github.com/ahausladen/DLangExtensions

The problem with preprocessors is that it kills the link between the original (prior to pre-processing) source code and the source code that Delphi compiles.
This means that you will not have debug info for your original source.
(unless you rewrite the map file).

Inlining
Depending on what you want to do you can use inlining to achieve almost the same efficiency as an intrinsic function. See: https://stackoverflow.com/a/6401833/650492

Construct your statements using intrinsic functions
If you have a code block consisting of instrinsic functions, the complete result will be evaluated at compile time, making the total construct work as if it was a intrinsic function.

Note the following (silly) example:

function FitsInRegister<T>: Boolean; inline;
begin
  if GetTypeKind(T) in [tkString, tkUString] then result:= false
  else 
  {$IFDEF CPU32BITS}
  Result:= SizeOf(T) <= 4;
  {$ELSEIF CPU64BITS}
  Result:= SizeOf(T) <= 8;
  {$ENDIF}
end;

Because it is inline and it only uses intrinsic functions (and compiler directives), the function will be resolved at compiletime to a constant and not generate any code.




回答2:


Can I write my own, to execute routine at compile-time and use the result as constant?

No you cannot. These functions are built in to the compiler and if offers no extension mechanism to allow third parties to supply built in functions.



来源:https://stackoverflow.com/questions/32141319/how-to-write-delphi-compile-time-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!