Pointer Arithmetic in Delphi


Delphi is based on Object Pascal, which is a great programming language. Delphi is also a RAD (Rapid Application Development) tool for Windows, Android, iOS. It can be compiled for both 32-bit and 64-bit native code. In Delphi, you have powerful stuffs such as pointers as other programming languages such as C/C++. With pointers, you can increment or decrement and do some arithmetic. For example,

var
    p: PInteger;
    q: array [1..3] of integer;
begin
    p := @q[1];
    p^ := 1;
    Inc(p);
    p^ := 2;
    Inc(p);
    p^ := 3;
end;

However, if you want to use pointers in an expression, such as,

Pointer(Integer(data) + 2); // data is a pointer

you can cast it first to numerical numbers (treat pointers as integers). Some people prefer casting to unsigned integers (LongWord) instead of Integer because it doesn’t make sense for negative memory address.

Noted, that on 64-bit OS, the pointer is actually 8 size instead of 4 size, so therefore, the above castings will not work on 64-bit OS, which should be replaced by nativeint or nativeuint which is size 4 under 32-bit compiler and size 8 under 64-bit compiler.

Before Delphi 2009, when {$POINTERMATH ON} is not present, therefore, you could cast the pointers to PAnsiChar which allows pointer arithmetic (without casting to integers), on and after D2009, you could cast the pointers to PByte and turn the compiler directive on {$POINTERMATH ON} which is local scope (effects in current unit) for other types.

As a general rule of thumb, pointers are not numbers and you should avoid converting them to be integers. It is almost always best to let pointers be pointers. You can always perform pointer arithmetic on types PAnsiChar, PWideChar and PByte, and for other pointer types you can use {$POINTERMATH ON} to enable pointer arithmetic.

The following will be recommended on and after D2009,

{$POINTERMATH ON}
Pointer(PByte(data) + 2); // data is a pointer

And use the following before D2009, e.g. D2007

Pointer(PAnsiChar(data) + 2); // data is a pointer

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
407 words
Last Post: GD Star Rating Plugin Not Properly Working if CloudFlare is On
Next Post: Reverse String in C/C++ (String Reversal Algorithm)

The Permanent URL is: Pointer Arithmetic in Delphi

Leave a Reply