Board logo

Subject: Absolute Address(绝对地址)的用法 [Print This Page]

Author: skyjacker    Time: 2007-6-21 15:07     Subject: Absolute Address(绝对地址)的用法

Written by SkyJacker for future reference 2007.06
http://bbs.cnpack.org
QQ Group: 130970

From Delphi Help:

Absolute Address(绝对地址)的用法

You can create a new variable that resides at the same address as another variable.
To do so, put the directive absolute after the type name in the declaration of the new variable,
followed by the name of an existing (previously declared) variable. For example,
你可以创建一个新的变量,它可以和另一个变量位于相同的地址。(reside 翻译成"同居"会容易记吧 ^_^)
实现如下,将指示字 absolute 放在新变量的类型名后面, absolute 的后面是已存在变量(前面声明的)的名。
例子如下:

var

  Str: string[32];
  StrLen: Byte absolute Str;

specifies that the variable StrLen should start at the same address as Str.
Since the first byte of a short string contains the string's length, the value of StrLen is the length of Str.
You cannot initialize a variable in an absolute declaration or combine absolute with any other directives.
定义的 StrLen 变量和 Str 是同一个起始地址。
因为短字符串的第一个字节存放的是字符串的长度,因此 StrLen 的值是 Str 的长度.
不能初始化用 absolute 声明的变量和任何包含 absolute 的指示变量.


译者注:
使用在 string 时注意事项:
必须使用这种 string[N] 形式(短字符串), 并且 Str 需要初始化, 否则 StrLen 是个随机数

下面两个 Double 函数来自 jcl, 照虎画猫就画了 Single.
比偶以前的 FloatHexStrToFloat 等函数简洁多了.

function DoubleToHex(const D: Double): string;
var
  Overlay: array [1..2] of Longint absolute D;
begin
  // Look at element 2 before element 1 because of "Little Endian" order.
  Result := IntToHex(Overlay[2], 8) + IntToHex(Overlay[1], 8);
end;

function HexToDouble(const Hex: string): Double;
var
  D: Double;
  Overlay: array [1..2] of Longint absolute D;
begin
  if Length(Hex) <> 16 then
  begin
    Result := 0;
    Exit;
  end;
  Overlay[1] := StrToInt('$' + Copy(Hex, 9, 8));
  Overlay[2] := StrToInt('$' + Copy(Hex, 1, 8));
  Result := D;
end;

function SingleToHex(const D: Single): string;
var
  Overlay: Longint absolute D;
begin
  Result := IntToHex(Overlay, 8);
end;

function HexToSingle(const Hex: string): Single;
var
  D: Single;
  Overlay: Longint absolute D;
begin
  if Length(Hex) <> 8 then
  begin
    Result := 0;
    Exit;
  end;
  Overlay := StrToInt('$' + Hex);
  Result := D;
end;
Author: kendling    Time: 2007-6-21 16:52

强,这种变量定义方法我还是第一次看到。




Welcome to CnPack Forum (http://bbs.cnpack.org/) Powered by Discuz! 5.0.0