Georgi Bonchev
Georgi Bonchev

Reputation: 300

Is there a way to determine the type of a Pointer?

Let's say I have these types and variables:

type

TMyStruct1 = record
  Int1        : Integer;
  Int2        : Integer;
  Str1        : String;
  Str2        : String;
end;
PMyStruct1 = ^TMyStruct1;

TMyStruct2 = record
  Int1        : Integer;
  Int2        : Integer;
  Str1        : String;
  Str2        : String;
end;
PMyStruct2 = ^TMyStruct2;

var

P1: PMyStruct1;
P2: PMyStruct2; 

I have a function that acepts Pointer as an argument. Is there a way to determine if the function is called with P1 or P2 variable?

Something like:

function DoSomething(P: Pointer);
begin
 //if  ??? Type(P) = PMyStruct1 ??? then ....

Upvotes: 3

Views: 589

Answers (3)

Marcodor
Marcodor

Reputation: 5741

A pointer is a kind of variable that can store a memory address or a special nil value.

It can point to anything, to a valid or invalid, already destroyed object, to a variable, to a third char in a string or to another pointer.

But it store just the memory address, nothing more. There is no way to know the type from a memory address. If you need the type or other info, you should take care yourself about it.

For homogeneous structures an approach is to store its type or version in the first byte of the structure and later pointing a matched PStructureX on the pointer address, like in Ken's answer.

Upvotes: 0

Ken Bourassa
Ken Bourassa

Reputation: 6467

You can achieve that by adding a "standard header" to your structure. In your case, a simple field indicating the type of your structure would be sufficient.

const 
  STRUCT_1 = 1;
  STRUCT_2 = 2;
type

TMyStruct1 = record
  StructType  : Integer
  Int1        : Integer;
  Int2        : Integer;
  Str1        : String;
  Str2        : String;
end;
PMyStruct1 = ^TMyStruct1;

TMyStruct2 = record
  StructType  : Integer
  Int1        : Integer;
  Int2        : Integer;
  Str1        : String;
  Str2        : String;
end;
PMyStruct2 = ^TMyStruct2;

var

P1: PMyStruct1;
P2: PMyStruct2;

function DoSomething(P: Pointer);
begin
  case PInteger(P)^ of //points to StructType
    STRUCT_1 : ;
    STRUCT_2 : ;
  end;
end;

Whoever is calling your function would be responsible to properly feed the StructType field.

As a forward compatibility measure, you could also add a "StructSize" field in case you end up needing multiple version of each structure.

This kind of type checking is "weak", in the sense that there is no guarantee the pointer is of the proper type, it only checks if the first 4 bytes it points to contains STRUCT_1 or STRUCT_2.

Now, if you don't control the definition of those records, you're out of luck.

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 612794

Is there a way to determine if the function is called with P1 or P2 variable?

No there is not.

Upvotes: 4

Related Questions