如何定义适用于本地过程的过程类型? [英] How to define a procedure type that works for a local procedure?

查看:51
本文介绍了如何定义适用于本地过程的过程类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自定义线程 TMyThread 中创建请求队列,并且很难定义可用于子例程的过程类型.我有一个代表请求的记录,一个对应的记录指针以及一个在记录中使用的过程类型,并且使用了记录指针...

I'm creating a request queue in a custom thread TMyThread and I'm having difficulties defining a procedure type which can be used for a subroutine. I have a record which represents the request, a corresponding record pointer, and a procedure type which is used in the record and uses the record pointer...

type
  PRequest = ^TRequest;

  TResponseProc = procedure(Sender: TMyThread; Request: PRequest);

  TRequest = record
    Request: String;
    Proc: TResponseProc;
    Response: String;
  end;

问题是,当我实现名为 ResponseProc 的子例程并尝试将 ResponseProc 分配给 TResponseProc 时,它不起作用,并且IDE返回此错误消息:

The problem is, when I implement a subroutine named ResponseProc and try to assign ResponseProc to a TResponseProc, it doesn't work, and the IDE returns this error message:

[DCC Error] MyProject.dpr(42): E2094 Local procedure/function 'ResponseProc' assigned to procedure variable

如何定义此过程类型 TResponse 并将其与子例程一起使用?

How do I define this procedure type TResponse and use it with a subroutine?

推荐答案

记录和过程声明很好.错误消息表明您正在使用本地过程,该过程是在另一个函数的范围内定义的.您不能使用指向此类函数的指针,因为它们需要额外的调用工作,而这些不能用普通的函数指针来表示.(编译器不允许创建指向调用者不知道如何使用的函数的指针.)

The record and procedure declarations are fine. The error message indicates that you're using a local procedure, which is one that's defined inside the scope of another function. You cannot use pointers to such functions because they require extra work to call, which cannot be expressed in an ordinary function pointer. (The compiler disallows creating pointers to functions that a caller won't know how to use.)

解决方案是将您的函数移出到您在其中定义的任何其他函数.如果这很难做到,因为内部函数使用外部函数中的变量,那么您必须弄清楚将它们的值传递给其他函数的其他方法,例如通过将它们作为参数传递,也许使它们成为该请求记录的其他成员.

The solution is to move your function outside whatever other function you defined it in. If that's hard to do because the inner function uses variables from the outer function, then you'll have to figure out some other way of getting their values to the other function, such as by passing them as parameters, perhaps making them additional members of that request record.

另一种选择是使用过程引用,然后将本地过程定义为匿名过程.它可以访问局部变量,尽管只有Delphi和C ++ Builder会知道如何调用它,所以如果需要外部API兼容性,则不是一种选择.

Another option is to use a procedure reference, and then define the local procedure as an anonymous procedure instead. It can access local variables, although only Delphi and C++ Builder will know how to invoke it, so it's not an option if you need external API compatibility.

这篇关于如何定义适用于本地过程的过程类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆