Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a variant from a pointer in Delphi?

I need to be able to convert a naked pointer to a variant. I know that the pointer points to a variant, but I can't seem to get it back out. A straight cast (as I pretty much thought) fails:

Result := Variant(FAddress)^

returns a compiler error: [DCC Error] E2089 Invalid typecast

I've scoured the variants.pas unit as well, but nothing jumped out at me.

Obviously I'm missing something. What is the way to do this?

like image 811
Nick Hodges Avatar asked Apr 13 '11 18:04

Nick Hodges


People also ask

How do I use pointers in Delphi?

Pointers are typed to indicate the kind of data stored at the addresses they hold. The general-purpose Pointer type can represent a pointer to any data, while more specialized pointer types reference only specific types of data. The PByte type is used for any byte data that is not character data.

What is a variant in Delphi?

The Variant type is a dynamic type. A Variant variable can change type at runtime, sometimes storing an integer, other times a string, and other times an array. Delphi automatically casts numbers, strings, interfaces, and other types to and from Variant s as needed.

Does Delphi have pointers?

Another important pointer concept in Delphi is procedure and method pointers. Pointers that point to the address of a procedure or function are called procedural pointers. Method pointers are similar to procedure pointers. However, instead of pointing to standalone procedures, they must point to class methods.


1 Answers

If the pointer points at a Variant, then its type is PVariant. Type-cast it to that, and then dereference:

Result := PVariant(FAddress)^;

Better yet, declare FAddress with the right type to begin with, and then you don't need to typecast:

var
  FAddress: PVariant;

Result := FAddress^;

The compiler considers your attempted type-cast invalid because Variant is a bigger type than Pointer is. The compiler doesn't know where to get the additional data to create a full Variant value. And if the type-cast were valid, the use of the ^ operator isn't allowed on Variants anyway. You might have gotten away with this:

Result := Variant(FAddress^);

I've never liked that; if FAddress is an untyped pointer, then dereferencing it yields a value without any size or type at all, and it's just weird to type-cast such a thing.

like image 62
Rob Kennedy Avatar answered Nov 04 '22 05:11

Rob Kennedy