Главная страница | назад





Article #16295: Working with objects and functions in other units

 Question and Answer Database
FAQ1295D.txt Working with objects and functions in other units
Category :Object Pascal
Platform :All
Product :All 32 bit
Question:
How can I call a function or procedure in another unit,
or retrieve and set the value of a variable in another unit?
Answer:
Anything defined in the interface section of a unit is visible
and callable from another unit that uses that unit. This
includes Types, Constants, Classes, Functions, and Procedures.
You should simply add the unit's name you want to use to the
uses clause of the unit you wish to use it from. Unless
necessary, you should define the uses clause in the
implementation section, to help avoid circular reference
errors. This is where two units depend on each other in their
interface sections.
If you have a function in the current unit that has the same
name as a function in another unit your wish to call, you can
preface the function name with the unit name to fully qualify
it.
The following example demonstrates calling functions and
procedures and accessing variables in another unit:
Example:
{Code for unit2}
unit Unit2;
interface
procedure SomeProcedure(i : integer);
function SomeFunction(i : integer) : integer;
var
SomeInteger : integer;
implementation
procedure SomeProcedure(i : integer);
begin
SomeInteger := i;
end;
function SomeFunction(i : integer) : integer;
begin
Result := SomeInteger;
SomeInteger := i;
end;
end.
{Code for unit1's implementation section:}
implementation
uses
Unit2;
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
SomeProcedure(10);
ShowMessage(IntToStr(SomeFunction(12)));
ShowMessage(IntToStr(SomeInteger));
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
{Lets do the same thing as Button1Click but fully
qualify the names}
Unit2.SomeProcedure(10);
ShowMessage(IntToStr(Unit2.SomeFunction(12)));
ShowMessage(IntToStr(Unit2.SomeInteger));
end;
7/16/98 4:31:28 PM

Last Modified: 01-SEP-99