Neat little trick to easily copy structures

Coding and general discussion relating to the compiler

Moderators: David Barker, Jerry Messina

Post Reply
bernardj
Posts: 14
Joined: Fri Jul 10, 2015 7:52 pm

Neat little trick to easily copy structures

Post by bernardj » 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):

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
To copy the structure as shown above would require code like this (one line for each member of the structure):

Code: Select all

Dim cs1, cs2 as ClientStruct

cs2.ClientID = cs1.ClientID
cs2.IPAddress = cs1.IPAddress
...
...
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):

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
This works for me, hope you find it useful as well. (Remember the ByRefs)

Jerry Messina
Swordfish Developer
Posts: 1469
Joined: Fri Jan 30, 2009 6:27 pm
Location: US

Re: Neat little trick to easily copy structures

Post by Jerry Messina » Mon May 22, 2017 8:43 pm

You can copy structures a lot easier than that...

Code: Select all

Dim cs1, cs2 as ClientStruct

// copy structure cs2 to cs1
cs1 = cs2
It generates code to do a fast byte-by-byte copy... hard to beat it speed or size-wise.

Post Reply