Sunday, February 19, 2023

How to call a C function in Structure Text (Twincat ) ?

In the previous post I created a function returning a 2-D array in C . In this post propose some steps to call that function within a Twincat structure text program. To call a C function like struct Array2D matrixMultiplication(struct Array2D a, struct Array2D b) in TwinCAT Structured Text (ST), you can use the C-Callable Function Blocks (CCFBs) provided by TwinCAT. Here's an example of how to use a CCFB to call the matrixMultiplication function in ST:
  

PROGRAM MAIN
VAR
    a : ARRAY[1..3, 1..3] OF INT := [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
    b : ARRAY[1..3, 1..3] OF INT := [ [9, 8, 7], [6, 5, 4], [3, 2, 1] ];
    c : ARRAY[1..3, 1..3] OF INT;
    a2d : STRUCT
        array : ARRAY[1..3, 1..3] OF INT;
    END_STRUCT;
    b2d : STRUCT
        array : ARRAY[1..3, 1..3] OF INT;
    END_STRUCT;
    c2d : STRUCT
        array : ARRAY[1..3, 1..3] OF INT;
    END_STRUCT;
    hLib : UINT := 0;
    pFunc : UINT := 0;
    result : INT := 0;
END_VAR

// Load the C library containing the matrixMultiplication function
hLib := SysLibLoad('MyLibrary.dll');

// Get the address of the matrixMultiplication function
pFunc := SysLibGetProcAddress(hLib, 'matrixMultiplication');

// Convert the input matrices to C-compatible data types
a2d.array := a;
b2d.array := b;

// Call the matrixMultiplication function using a CCFB
result := CCFBInvoke(pFunc, ADR(a2d), ADR(b2d), ADR(c2d));

// Check the result of the function call
IF result = 0 THEN
    // Convert the output matrix to ST-compatible data type
    c := c2d.array;
ELSE
    // Handle the error
END_IF

// Unload the C library
SysLibFree(hLib);


  
In this example, we define the input matrices a and b, and the output matrix c as ST arrays.

 We also define three STRUCT types a2d, b2d, and c2d, which have the same layout as the struct Array2D type used in the matrixMultiplication function.

Next, we load the C library containing the matrixMultiplication function using SysLibLoad, and get the address of the function using SysLibGetProcAddress

We then use the CCFBInvoke function to call the matrixMultiplication function, passing in the converted input matrices a2d and b2d, and the output c2d

 If the function call succeeds, the resulting c2d structure contains the output matrix, which we convert back to an ST array and store in c. If the function call fails, we can handle the error appropriately.

 Finally, we unload the C library using SysLibFree

 Note that you will need to compile the matrixMultiplication function into a DLL or shared library in order to load and call it from TwinCAT

 I will try to make a youtube video on this post as soon as possible.

No comments:

Post a Comment