zoukankan      html  css  js  c++  java
  • 获取函数的地址(三种方法,分别是@,Addr,MethodAddress)

    问题来源: http://www.cnblogs.com/del/archive/2008/07/30/1039045.html#1272783



    在编译器看来, 重载函数根本就是完全不同的几个函数, 当然就会有不同的函数地址; 我们用常规方法获取的地址只是第一种重载的地址.



    代码文件:


    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs;
    
    type
      TForm1 = class(TForm)
        procedure FormCreate(Sender: TObject);
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    {先举例两个重载函数}
    function MyFun(s: string): string; overload;
    begin
      Result := s;
    end;
    
    function MyFun(i: Integer): string; overload;
    begin
      Result := IntToStr(i);
    end;
    
    {分别获取重载函数的地址}
    procedure TForm1.FormCreate(Sender: TObject);
    type {需要先定义两个方法类型, 参数分别对应上面的重载函数}
      TF1 = function(s: string): string;
      TF2 = function(i: Integer): string;
    var
      f1: TF1; {对应重载一}
      f2: TF2; {对应重载二}
      s1,s2: string;
    begin
      f1 := MyFun; {让 f1 指向重载一}
      f2 := MyFun; {让 f2 指向重载二}
    
      {测试函数}
      s1 := f1('abc');
      s2 := f2(123);
      ShowMessageFmt('%s, %s', [s1,s2]); {abc, 123}
    
      {前两个值分别是两个重载函数的地址; 第三个值是根据函数名获取的, 它和第一种重载的地址相同}
      ShowMessageFmt('%p, %p, %p', [@f1, @f2, @MyFun]);
    
      {另一种方法}
      ShowMessageFmt('%p, %p, %p', [Addr(f1), Addr(f2), Addr(MyFun)]);
    
      {如果是类 published 区中的方法, 也可以用 MethodAddress 获取地址}
    end;
    
    end.

    http://www.cnblogs.com/del/archive/2008/07/30/1256889.html

  • 相关阅读:
    323. Number of Connected Components in an Undirected Graph
    418. Sentence Screen Fitting
    417. Pacific Atlantic Water Flow
    416. Partition Equal Subset Sum
    415. Add Strings
    245. Shortest Word Distance III
    [AHOI2009]维护序列
    [洛谷P1439]排列LCS问题
    [Vijos P1369]难解的问题
    [codevs3657]括号序列
  • 原文地址:https://www.cnblogs.com/findumars/p/6028463.html
Copyright © 2011-2022 走看看