Access Data via Symbol handles

The Read/Write Access by handle solves the issue of directly accessing the process image like the symbol path access. Because the address is accessed indirectly by the symbol path creating a variable handle, the read/write works also when the data object has changed its position within the process image.

However the cost for this are two extra ADS communication roundtrips by the 'CreateVariableHandle' and 'DeleteVariableHandle' calls compared to the IndexGroup/IndexOffset access methods. It is the responsibility of the application code to optimize these accesses.

Example

Access symbolic values by handle

using (TcAdsClient client = new TcAdsClient())
{
    int varHandle = 0;
    client.Connect(AmsNetId.Local, 851);
    try
    {
    UInt16 valueToRead = 0;
    UInt16 valueToWrite = 42;

    // Create the Variable Handle
    varHandle = client.CreateVariableHandle("MAIN.testVar"); //Test Var is defined as PLC INT

    // Write an UINT16 Value
    AdsStream writeStream = new AdsStream(sizeof(UInt16));
    AdsBinaryWriter writer = new AdsBinaryWriter(writeStream);
    writer.Write(valueToWrite); // Marshal the Value
    adsClient.Write(varHandle, writeStream,0,sizeof(uint));

    // Read an UINT16 Value
    AdsStream readStream = new AdsStream(sizeof(UInt16));
    adsClient.Read(varHandle, readStream, 0, sizeof(UInt16));
    readStream.Position = 0;
    AdsBinaryReader reader = new AdsBinaryReader(readStream);
    valueToRead = reader.ReadUInt16(); // Unmarshal the Value
    }
    finally
    {
    // Unregister VarHandle after Use
    client.DeleteVariableHandle(varHandle);
    }
}