Creating an FB in the PLC that creates the C++ object and offers its functionality
- 1. Create a PLC and append a new function block there.
This Proxy function block should provide the functionality that was programmed in C++. It manages this via an interface pointer that was defined by C++ and is known in the PLC due to the TMC description file.
- 2. In the declaration part of the function block declare as an output an interface pointer to the interface (IIncrement) which later provides the functionality outward.
- 3. Create a library ID, class ID, and the interface ID as member variables, as shown in the previous step.
While the interface ID is already available via a global list, the library ID and the class ID, provided they are not yet supposed to be known, are determined by other means. One possible way to do this is to create an instance temporarily and take the information from the dialog before it can be deleted again:
- 4. Add the FB_init constructor method to the PLC Proxy function block.
For the case, that it is not an online change but rather the initialization of the function block, a new TcCOM object (Class instance of the specified class) is created and the interface pointer to the specified interface is obtained.
First, the versioned class ID is calculated from the library ID and the class ID using the F_GetClassIdVersioned() method. Then the used FW_ObjMgr_CreateAndInitInstance() function is also given the name and the target state of the TcCOM object. These two parameters are declared here as input parameters of the FB_init method, whereby they are to be specified in the instantiation of the Proxy function block. The TwinCAT C++ class to be instantiated does without TcCOM initialization data and without TcCOM parameters.
With this function call the object itself counts up a reference counter.
- 5. It is imperative to release the used reference again and to delete the object, provided it is no longer being used. To this end call the FW_ObjMgr_DeleteInstance() function in the FB_exit destructor of the function block.
- This completes the implementation of the Proxy function block.
- 6. Declare an instance of the Proxy function block to call the methods provided via the interface in the application. The calls themselves take all place over the interface pointer defined as output of the function block. As is typical for pointers a prior null check must be made. Then the methods can be called directly, also via Intellisense.
- The sample is ready for testing.