Working with handles of PLC variables

System requirements:

All the required handles can be fetched once at the start of the application, and released again when the application is closed. Continuously requesting and releasing handles places unnecessary loading on the system.

Handles that have already been requested become invalid when TwinCAT is restarted, and must be requested again. The same applies after 'Rebuild All' in the PLC. 'Rebuild All' causes a complete new program to be loaded into the runtime system, so that any handles that have already been requested are invalid, and are automatically released by TwinCAT. The handles that are no longer required must always be released. This can, however, only be done if the TwinCAT system is still running. If the TwinCAT system has already stopped, then all the handles are automatically released.

Connect with the first runtime system on the local PC and fetch the handle of the PLC variables:

procedure TForm1.FormCreate(Sender: TObject);
var adsResult : Integer;
begin
   AdsOcx1.AdsAmsServerNetId := AdsOcx1.AdsAmsClientNetId;
   AdsOcx1.AdsAmsServerPort := 801;
   adsResult := AdsOcx1.AdsCreateVarHandle( 'MAIN.VARINTARRAY', hVar );
   if adsResult <> 0 then
      ShowMessage( Format( 'AdsCreateVarHandle() error:%d', [adsResult] ) );
end;

Release the handle when the application is closed:

procedure TForm1.FormDestroy(Sender: TObject);
var adsResult : Integer;
begin
   adsResult := AdsOcx1.AdsDeleteVarHandle( hVar );
   if AdsResult <> 0 then
      ShowMessage( Format( 'AdsDeleteVarHandle() error:%d', [adsResult] ) );
   hVar := 0;
end;

Language / IDE

Unpack sample program

Delphi XE2

Sample05.exe

Delphi 7 or higher (classic)