简体   繁体   中英

How to get method address of a generic class method?

We can get a class method address by with this code:

type
  TMyClass = class
    procedure A;
  end;

var P: Pointer;
begin
  P := @TMyClass.A;
end;

For a generic class, how to get a method address from a generic class?

type
  TGeneric<T> = class
    procedure A;
  end;


var P: Pointer;
begin
  P := @TGeneric<T>.A;  // <--- compilation error
end.

TGeneric<T> is an open type, in other words not all type parameters have been specified. Your code fails because there is no single address for a method of an open type. Different concrete instantiations have different addresses. For example TGeneric<Integer>.A is a different method from TGeneric<string>.A , and consequently has a different address.

Unless you supply a concrete value for the generic type parameter, this construct can have no meaning. Consider this program:

{$APPTYPE CONSOLE}

type
  TGeneric<T> = class
    class procedure A;
  end;

class procedure TGeneric<T>.A;
var
  P: Pointer;
begin
  P := @TGeneric<T>.A;
  Writeln(NativeInt(P));
end;

begin
  TGeneric<Integer>.A;
  TGeneric<string>.A;
end.

This program outputs two values which are different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM