I am trying to call methods by name in a firemonkey project. But so far no luck.
Below is my code:
type
TExecute = procedure of object;
TUpdates= class(TDataModule)
procedure UpdateToVersion(Version: Integer);
private
procedure UpdateToVersion1;
procedure UpdateToVersion2;
procedure UpdateToVersion3;
procedure Call(Name: string);
public
end;
procedure TUpdates.Call(Name: String);
var
m:TMethod;
Exe:TExecute;
begin
m.Data := pointer(Self);
m.Code := Self.MethodAddress(Name);
Exe := TExecute(m);
Exe;
end;
procedure TUpdates.UpdateToVersion(Version: Integer);
begin
Call('UpdateToVersion'+version.ToString);
end;
procedure TUpdates.UpdateToVersion1;
begin
//code
end;
procedure TUpdates.UpdateToVersion2;
begin
//code
end;
procedure TUpdates.UpdateToVersion3;
begin
//code
end;
Results: When I call for example UpdateToVersion(1) I get an access violation and procedure UpdateToVersion1 doesn't get called.
I got this code from an example from the link below: http://www.swissdelphicenter.ch/torry/showcode.php?id=799
MethodAddress
requires that the method is published, as is the method in the example code. Your methods are private. Hence MethodAddress
fails and returns nil
.
Solve the problem by publishing the methods.
If you wish to perform this sort of task with non-published methods then you will need to use enhanced RTTI.