CnPack Forum


 
Subject: Absolute Address(绝对地址)的用法
skyjacker
版主
Rank: 7Rank: 7Rank: 7
茶农


UID 2239
Digest Posts 9
Credits 617
Posts 269
点点分 617
Reading Access 100
Registered 2006-6-8
Status Offline
Post at 2007-6-21 15:07  Profile | Blog | P.M.  | QQ
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;




一壶清茶煮青春.
Top
kendling (小冬)
高级版主
Rank: 8Rank: 8
MyvNet


Medal No.1  
UID 703
Digest Posts 5
Credits 978
Posts 580
点点分 978
Reading Access 101
Registered 2005-2-18
Location 广东
Status Offline
Post at 2007-6-21 16:52  Profile | Site | Blog | P.M.  | QQ | Yahoo!
强,这种变量定义方法我还是第一次看到。




小冬
http://MyvNet.com
Top
 




All times are GMT++8, the time now is 2024-11-22 06:42

    本论坛支付平台由支付宝提供
携手打造安全诚信的交易社区 Powered by Discuz! 5.0.0  © 2001-2006 Comsenz Inc.
Processed in 0.009491 second(s), 8 queries , Gzip enabled

Clear Cookies - Contact Us - CnPack Website - Archiver - WAP