c++twincatsttwincat-ads

How to call a method within a Function block in Twincat ST through C++ ADS code?


That is I want to call a method, suppose TestMethod of FB_CALCULATOR, from C++ code using the ADS libraries. I'm unable to find examples for this in C++. The available examples seem to be only for C#, and these functions do not exist in their C++ ADS Libraries. I have tried going through Beckhoff infosys but haven't found anything useful for this in C++.


Solution

  • This is lifted straight from https://github.com/Beckhoff/ADS/issues/131:

    typedef struct
    {
        unsigned long a;
        unsigned long b;
    } MethodParameters;
    
    // ...
    
    long nErr, nPort;
    AmsAddr Addr;
    PAmsAddr pAddr = &Addr;
    ULONG lHdlVar, rValue;
    char szVar[] = {"MAIN.foo#DoAdd"};
    MethodParameters params;
    
    // ...
    
    nPort = AdsPortOpen();
    nErr = AdsGetLocalAddress(pAddr);
    if (nErr)
    {
        cerr << "Error: AdsGetLocalAddress: " << nErr << '\n';
    }
    
    pAddr->port = 851;
    
    nErr = AdsSyncReadWriteReq(pAddr, ADSIGRP_SYM_HNDBYNAME, 0x0, sizeof(lHdlVar), &lHdlVar, sizeof(szVar), szVar);
    if (nErr)
    {
        cerr << "Error: AdsSyncReadWriteReq: " << nErr << '\n';
    }
    
    params.a = 5;
    params.b = 5;
    
    nErr = AdsSyncReadWriteReq(pAddr, ADSIGRP_SYM_VALBYHND, lHdlVar, sizeof(rValue), &rValue, sizeof(params), &params);
    if (nErr)
    {
        cerr << "Error: AdsSyncReadWriteReq: " << nErr << '\n';
    }
    
    cout << "rValue: " << rValue;
    
    nErr = AdsSyncWriteReq(pAddr, ADSIGRP_SYM_RELEASEHND, 0, sizeof(lHdlVar), &lHdlVar);
    if (nErr)
    {
        cerr << "Error: AdsSyncWriteReq: " << nErr << '\n';
    }
    
    nErr = AdsPortClose();
    if (nErr)
    {
        cerr << "Error: AdsPortClose: " << nErr << '\n';
    }