Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for local variable absolute to another variable with some offset

Tags:

delphi

Is there a way that I can declare a variable with an absolute address that has some offset to the variable that it refers to. For instance, instead of:

function RefCount(const s: string): Integer;
begin
  Result := PInteger(Integer(s) - 8)^;
end;


is there some way that I can do:

function RefCount(const s: string): Integer;
var
  Count: PInteger absolute s {- 8 ?} ;
begin
  Result := Count^;
end;

(The example is to illustrate only, it is not necessarily useful..)

like image 474
Sertac Akyuz Avatar asked Dec 16 '11 22:12

Sertac Akyuz


2 Answers

No, I don't think there is an 'extended syntax' of the absolute keyword. The documentation is here, and, as far as I know, there are no undocumented features related to this keyword.

like image 60
Andreas Rejbrand Avatar answered Sep 28 '22 18:09

Andreas Rejbrand


There is no syntax for what you ask.

What you can do, however, is use pointer arithmetic (if you are using a version that supports it), eg:

function RefCount(const s: string): Integer; 
begin 
  if s <> '' then
    Result := (PInteger(s) - 2)^; 
  else
    Result := 0; 
end; 

A more reliably approach is to use the StrRec record type instead, which is what a String actually contains internally:

function RefCount(const s: string): Integer; 
begin 
  if s <> '' then
    Result := (PStrRec(s) - 1)^.refCnt
  else
    Result := 0;
end; 

Or, the non pointer arithmetic version:

function RefCount(const s: string): Integer; 
begin 
  if s <> '' then
    Result := PStrRec(LongInt(s) - SizeOf(StrRec))^.refCnt
  else
    Result := 0;
end; 

BTW, starting with D2009+, the System unit has its own StringRefCount() function that retreive a String's reference count.

like image 33
Remy Lebeau Avatar answered Sep 28 '22 19:09

Remy Lebeau