Delphi:调用名称存储在字符串中的函数 [英] Delphi: Call a function whose name is stored in a string
本文介绍了Delphi:调用名称存储在字符串中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Delphi中是否可以调用名称存储在字符串中的函数?
Is it possible to call a function whose name is stored in a string in Delphi?
推荐答案
请详细说明您要实现的目标.
Please give more details on what are you trying to achieve.
据我所知:
- 不可能像那样调用随机函数.
- 对于类和对象函数 (MyObject.Function),这可以通过 RTTI 完成,但需要大量工作.
- 如果您只需要调用一种特定类型的函数(例如 function(integer, integer): string),那就容易多了.
对于最后一个,声明一个函数类型,然后获取一个函数指针并像这样进行转换:
For the last one, declare a function type, then get a function pointer and cast it like this:
type
TMyFuncType = function(a: integer; b: integer): string of object;
TMyClass = class
published
function Func1(a: integer; b: integer): string;
function Func2(a: integer; b: integer): string;
function Func3(a: integer; b: integer): string;
public
function Call(MethodName: string; a, b: integer): string;
end;
function TMyClass.Call(MethodName: string; a, b: integer): string;
var m: TMethod;
begin
m.Code := Self.MethodAddress(MethodName); //find method code
m.Data := pointer(Self); //store pointer to object instance
Result := TMyFuncType(m)(a, b);
end;
{...}
//use it like this
var MyClass: TMyClass;
begin
MyClass := TMyClass.Create;
MyClass.Call('Func1', 3, 5);
MyClass.Call('Func2', 6, 4);
MyClass.Destroy;
end.
这篇关于Delphi:调用名称存储在字符串中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文