Howto cast pointer to generic parameter type?

感情迁移 提交于 2019-12-03 15:43:35

You need to take the address of the location of the generic type parameter type, then typecast this address to a pointer to the desired type, and then dereference this pointer and assign into the resulting location. For example:

PObject(@Value)^ := Ptr;

The reason you can't just typecast a value of type T, where T is unconstrained, is that the compiler doesn't know the size of T; normally, non-numeric typecasts can only convert values into types that are of the same size.

Unfortunately, the compiler is not smart enough to figure out that a class-type constraint means that T is guaranteed to be the same size as a pointer.

Also, there is an issue with current Delphi 2009 generics with creating pointers to type parameter types. Generic pointers are not supported by the compiler, but the compiler permits this syntax inside classes:

type
  C<T> = class
  type
    PT = ^T; // UNSUPPORTED!
  end;

This may work for certain scenarios - and can be helpful for your specific problem - but it only works by accident and is not generally supported. Use at your own risk.

Try this:

Value := TObject (Ptr)

No need to cast more, as assigning the TObject to the generic class type variable is valid :)

But I do not know the reason why you cannot use T for casting in the first place...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!