Search code examples
functiondelphipointersdelphi-xe7tstringlist

Delphi XE7 Android how to store function pointers to later access?


When using Delphi to create Windows applications, it is possible do store function pointers in a TStringList variable, something like...

function n_func(var data: integer): integer;
begin
  //do something with data that will change its value
  Result := data;
end;

...

var
  ls: TStringList;
begin
  try
    ls := TStringList.Create;
    ls.AddObject('myfunc', TObject(@n_func));
    ...
    ...
  finally
    ls.Free;
  end;
end;

But this is not an option in Android, I've read this article that explains how to solve the problem when it's necessary to store a reference to an object. What could be a similar solution when it's necessary to store a reference to a function, that will be dynamically called later during the application execution?


Solution

  • Use a dictionary. Declare a type for the function:

    type
      TMyFuncType = reference to function(var data: integer): integer;
    

    Then a dictionary:

    var
      Dict: TDictionary<string, TMyFuncType>;
    

    Create one in the usual way:

    Dict := TDictionary<string, TMyFuncType>.Create;
    

    Add like this:

    Dict.Add('myfunc', n_func);
    

    Retrieve like this

    Func := Dict['myfunc'];
    

    Find out more from the documentation: http://docwiki.embarcadero.com/Libraries/en/System.Generics.Collections.TDictionary