function Test: string;
begin
  Result := 'function pointer test';
end;procedure TForm1.Button1Click(Sender: TObject);
var
  Func: function: string;
begin
  Func := Test;
  Caption := Func;
end;
//上面的调用一切正常
//现在我将函数写入类中调用
TBase = class
public
  function Test: string;
end;function TBase.Test: string;
begin
  Result := 'Object function pointer test';
end;procedure TForm1.Button2Click(Sender: TObject);
var
  Base: TBase;
  Func: function: string of Object;
begin
  Base := TBase.Create;
  try
    //这样调用TMethod(Func).Code也是nil
//    TMethod(Func).Code := Base.MethodAddress('Test'); 
    TMethod(Func).Code := TBase.MethodAddress('Test');
    if Assigned(TMethod(Func).Code) then
      Caption := Func;
  finally
    Base.Free;
  end;
end;
为什么TMethod(Func).Code还是nil,如果调用类中的函数指针应该怎样定义和调用?

解决方案 »

  1.   

    一个方法是这样 TMethod(Func).Code := @TBase.Test;
    另一个方法是
    TBase = class
    published
      function Test: string;  //声明为公布的
    end;
      

  2.   

    其实回调函数Call Back就是函数指针的典型应用,看看EnumWindows函数!
      

  3.   

    wx1452() 说的完全正确。TObject.MethodAddress Returns the address of a published method.
    把分都给他吧!————————————————————————————————————
    宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
    ————————————————————————————————————
      

  4.   

    把TBase 改成这样
      TBase = class
      published
        function Test: string;
      end;Returns the address of a published method.
    =========================================class function MethodAddress(const Name: ShortString): Pointer;DescriptionMethodAddress is used internally by the VCL streaming system. When reading an event property from a stream, MethodAddress converts a method name, specified by Name, to a pointer containing the method address. There should be no need to call MethodAddress directly.If Name does not specify a published method for the object, MethodAddress returns nil.
      

  5.   

    kao,困惑了我半天,原来这么简单,多谢多谢!
      

  6.   

    在这里没有必要使用MethodAddress.把TMethod(Func).Code := TBase.MethodAddress('Test');
    改为
    TMethod(Func).Code := @TBase.Test;
    注意不管是对象方法还是类方法,它的地址都在存储在类中,
    所以此时不能使用@Base.Test;