Join us today!

Using any structure...
 
Notifications
Clear all

Using any structure as an input to a function block

2 Posts
2 Users
4 Reactions
1,361 Views
twinControls
Posts: 115
Admin
Topic starter
(@twincontrols)
Member
Joined: 2 years ago

In this tutorial, we will explain how we can use any structure as an input to a function block so that we can create a more generic function block. 

Let's assume you have a struct called 'ST_Part' which contains all the fields of your part information:

TYPE ST_Part :
STRUCT
	sInfo : STRING;
	fWeight: REAL;
	fHeight : REAL;
	sBarcode : STRING;
END_STRUCT
END_TYPE

You want to store your part data in an xml file. At the time of the developing the xml file writer function block, you don't have any information about the struct yet and you want to be able to pass any struct to your function block.  We will examine two methods to achieve this. 

 

Method1 : Using T_Arg

You would need to add the Tc2_Utilities library in your project to be able to declare the variables as T_Arg. 

FB_XmlWriter: 

Declare your data input as T_Arg. 

FUNCTION_BLOCK FB_XmlWriter
VAR_INPUT
	tData : T_Arg;
END_VAR
VAR_OUTPUT
END_VAR
VAR
END_VAR

Inside the function block body, implement a check to see if this data is a byte buffer

IF (tData.eType = E_ArgType.ARGTYPE_BIGTYPE) THEN
	M_Write();
END_IF

 

In the main program, convert your ST_Part variable to T_Arg and pass it to FB_XmlWriter function block. 

PROGRAM MAIN
VAR
	fbXMLWriter : FB_XmlWriter;
	stPart : ST_Part;
	tArgPart : T_Arg;
END_VAR
tArgPart := F_BIGTYPE(pData:= ADR(stPart),cbLen:=SIZEOF(stPart));

fbXMLWriter(tData:=tArgPart);

 

Method 2 : Using PVOID 

PVOID is a pointer to a memory address, but it doesn't have any information about the data type. You'd need to use MEMCPY in the body of the function block since you'll be dealing with a memory address. 

FB_XmlWriter: 

FUNCTION_BLOCK FB_XmlWriter
VAR_INPUT
	tData : PVOID;
	nSize : UDINT;
END_VAR
VAR_OUTPUT
END_VAR
VAR
END_VAR

 

In the main program : 

PROGRAM MAIN
VAR
	fbXMLWriter : FB_XmlWriter;
	stPart : ST_Part;
END_VAR
fbXMLWriter(tData:= ADR(stPart) , nSize:= SIZEOF(stPart));

 

Reply
1 Reply
1 Reply
benhar-dev
(@benhar-dev)
Joined: 2 years ago

Eminent Member
Posts: 17

@twincontrols, I also like using ANY.

Method3 : Using ANY

FB_XmlWriter: 

FUNCTION_BLOCK FB_XmlWriter
VAR_INPUT
	tData : ANY;
END_VAR
VAR_OUTPUT
END_VAR
VAR
END_VAR

Inside the function block the variable tData will be replaced by a structure containing a few useful elements.  

tData.typeclass   // the type of the actual parameter
tData.pvalue      // the pointer to the actual parameter
tData.diSize      // the size of the data, to which the pointer points

In the main program : 

PROGRAM MAIN
VAR
	fbXMLWriter : FB_XmlWriter;
	stPart : ST_Part;
END_VAR
fbXMLWriter(tData:=stPart);

I used the same aproach in the tc3-count-structure-elements and tc3-push-pop-stack repos.

Reply
Share: