Neat little trick to easily copy structures
Posted: Mon May 22, 2017 8:20 pm
I hope this trick will help someone at some stage in copying structures:
Explanation:
Sample of a structure (old way):
To copy the structure as shown above would require code like this (one line for each member of the structure):
I would like to propose that the following is better way of doing:
1) Add a byte array to the structure together with the "union" keyword in the structure (with the array length equal to the actual size of structure), and
2) Use a loop to copy the structure (see Sub copyStruct).
Sample of a structure (new way):
This works for me, hope you find it useful as well. (Remember the ByRefs)
Explanation:
Sample of a structure (old way):
Code: Select all
Structure ClientStruct
ClientID As String(21)
IPAddress As String(17)
PortNumber As String(7)
LastConnectDate As String(18)
Reserved(35) As Byte
End Structure
Code: Select all
Dim cs1, cs2 as ClientStruct
cs2.ClientID = cs1.ClientID
cs2.IPAddress = cs1.IPAddress
...
...
1) Add a byte array to the structure together with the "union" keyword in the structure (with the array length equal to the actual size of structure), and
2) Use a loop to copy the structure (see Sub copyStruct).
Sample of a structure (new way):
Code: Select all
Structure ClientStruct
ClientID As String(21)
IPAddress As String(17)
PortNumber As String(7)
LastConnectDate As String(18)
Reserved(35) As Byte
byteArray(98) As Byte Union
End Structure
Sub copyStruct(ByRef src as clientStruct, ByRef dst as ClientStruct)
Dim i as byte
for i = 0 to bound(src.bytearray)
dst.bytearray(i) = src.bytearray(i)
next
end sub