5
votes

I have a problem with maintenance on an old Delphi program (D7). A lot of the program logic is in the DPR file (this is not a windowed program), with some units providing things like access to the database. We need to get some debug out of the DB unit, but the debug functionality is in the DPR. We can't easily strip the debug functionality out, because it uses stuff that's unique to the DPR, like its main pipe. Separating it out would be like trying to tease apart spaghetti and meatball sauce.

So how do we call a function that's declared at the DPR scope from a subordinate used unit? What's the equivalent of the :: operator in C++ ?

Please don't tell me to redesign the app. I'd love to, but we won't be given the necessary time. Plus if we redesigned this puppy, it wouldn't be in Delphi.

4

4 Answers

14
votes

You can declare a method variable in the unit that matches the signature of the function in the DPR. At the very beginning of the program you set the method variable to the function. Inside the unit you call the method variable.

Example:

(DPR)

uses
  Unit1;

function DoSomething(Par: Integer): Integer;
begin
...
end;

...
begin
  DoSomethingVar := DoSomething;
  ...
end;

(unit)

unit Unit1;

interface
...
var
  DoSomethingVar: function(Par1: Integer): Integer;
...
implementation
...
  SomeResult := DoSomethingVar(SomeParameter);
...
4
votes

You can't. The unit hierarchy is rigid.

There are two possible options:

  • pull out the relevant parts of the .dpr to a new unit. Keep in mind that moving uses to the implementation can break import cycles. The createform* stuff probably isn't safe to move, that would probably upset the project manager.
  • or define a few callback functions (function,method types, like functionpointer in C), and move code out of the relevant unit initialization to a procedure that you call from the .dpr if necessary.
3
votes

I don't know how to use functions from .dpr in other units, but if you have to change code simply change .dpr to normal unit and then use it's functions/routines in new .dpr and in others units.

0
votes

.dpr is the most fundmental pascal project file.

We can use any unit files in the project, and so, you can use the functions/procedures in the units.

If necessary, you can prefix the unit name for accessing the function/procedure.

If the function/procedure belongs to specific class, you need to create an instance to access the function/procedure because it's a method.

Anyway, Delphi uses object pascal as its core, you can access any necessary method/procedure/function/properties with legal pascal concepts and object pascal concepts.

No matter which file you need to call it, and the only one except is the decalaration file for some external library.