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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With