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完成,但这是很多工作。 >
- 如果你只需要调用一个特定类型的函数(比如说,函数(整数,整数):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屋!
查看全文