gpt4 book ai didi

delphi - 有没有一种干净的方法将匿名方法转换为指针?

转载 作者:行者123 更新时间:2023-12-03 15:23:20 25 4
gpt4 key购买 nike

我正在将匿名方法传递给外部函数。匿名方法是被积函数,外部函数将计算定积分。因为集成函数是外部的,所以它不理解匿名方法。所以我必须将匿名方法作为无类型指针传递。为了更清楚地说明这一点,它的运行方式如下:

function ExternalIntegrand(data: Pointer; x: Double): Double; cdecl;
begin
Result := GetAnonMethod(data)(x);
end;

....

var
Integrand: TFunc<Double,Double>;
Integral: Double;
....
Integral := CalcIntegral(ExternalIntegrand, CastToPointer(Integrand), xlow, xhigh);

这里 CalcIntegral 是将调用 ExternalIntegrand 的外部函数。反过来,它会获取传递的非类型化指针,检索匿名方法,并让它完成这项工作。

问题是我无法干净地编写CastToPointer。如果我这样做:

Pointer(Integrand)

编译器对象具有:

[dcc32 Error]: E2035 Not enough actual parameters

显然编译器正在尝试调用匿名方法。

我能够做到这一点:

function CastToPointer(const F: TFunc<Double,Double>): Pointer; inline;
begin
Move(F, Result, SizeOf(Result));
end;

或者这个:

function CastToPointer(const F: TFunc<Double,Double>): Pointer; inline;
var
P: Pointer absolute F;
begin
Result := P;
end;

但是,我无法像在将动态数组转换为指向数组的指针时那样使用简单的转换,这似乎有点令人难堪。

我意识到我可以传递保存匿名方法的变量的地址。像这样:

function ExternalIntegrand(data: Pointer; x: Double): Double; cdecl;
var
F: ^TFunc<Double,Double>;
begin
F := data;
Result := F^(x);
end;

....

Integral := CalcIntegral(ExternalIntegrand, @Integrand, xlow, xhigh);

但是,必须引入另一个间接级别似乎有点奇怪。

有人知道如何将匿名方法变量直接转换为指针吗?我确实意识到这种诈骗是值得怀疑的,但至少出于好奇我想知道是否可以做到。

最佳答案

您应该能够执行 Pointer((@Integrand)^) 这样您的调用将是:

Integral := CalcIntegral(ExternalIntegrand, Pointer((@Integrand)^), xlow, xhigh);

这是一种额外的间接级别,但不是:)

我通过与您的 CastToPointer 进行比较进行了测试,它有效:

program Project8;

{$APPTYPE CONSOLE}

{$R *.res}

{$T+}

uses
System.SysUtils;

function CastToPointer(const F: TFunc<Double,Double>): Pointer; inline;
begin
Move(F, Result, SizeOf(Result));
end;

var
Integrand: TFunc<Double,Double>;
Mypointer1: Pointer;
Mypointer2: Pointer;
begin
Integrand := function(x : double) : double
begin
result := 2 * x;
end;
Mypointer1 := Pointer((@Integrand)^);
Mypointer2 := CastToPointer(Integrand);
Assert(Mypointer1 = Mypointer2, 'Pointers don''t match!');
end.

关于delphi - 有没有一种干净的方法将匿名方法转换为指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30667777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com