Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a procedure type that works for a local procedure? [closed]

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;

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

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

like image 352
Jerry Dodge Avatar asked Feb 18 '23 08:02

Jerry Dodge


1 Answers

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.

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.

like image 68
Rob Kennedy Avatar answered May 01 '23 07:05

Rob Kennedy