|
|
Title | Use the RtlMoveMemory (CopyMemory) API function to copy memory from a 2-D array to a 1-D array |
Keywords | RtlMoveMemory, copy memory, CopyMemory, array, memory |
Categories | Tips and Tricks, Miscellany, Software Engineering |
|
|
This program copies part of a large 2-D array into a smaller 2-D array. It then uses RtlMoveMemory to copy the data one column at a time into a 1-D destination array. This operation is fast enough that it's not worth the effort for a program as small as this one. The technique could be handy for manipulating large arrays, however.
Note that Visual Basic stores its arrays in column order so a call to RtlMoveMemory copies data from a column not a row as you might expect.
|
|
Private Sub cmdCopy_Click()
Dim rmin As Integer
Dim rmax As Integer
Dim cmin As Integer
Dim cmax As Integer
Dim r As Integer
Dim c As Integer
Dim in_array() As Byte
Dim out_array() As Byte
Dim idx As Integer
Dim bytes_per_col As Long
Dim wid As Single
rmin = CInt(txtMinRow.Text)
rmax = CInt(txtMaxRow.Text)
cmin = CInt(txtMinCol.Text)
cmax = CInt(txtMaxCol.Text)
' Highlight the selected data.
For r = 0 To MAX_ROW
For c = 0 To MAX_COL
m_InBoxes(r, c).BackColor = vbWhite
m_InBoxes(r, c).ForeColor = vbBlack
Next c
Next r
For r = rmin To rmax
For c = cmin To cmax
m_InBoxes(r, c).BackColor = vbBlack
m_InBoxes(r, c).ForeColor = vbWhite
Next c
Next r
' Copy the inputs into in_array.
ReDim in_array(0 To MAX_ROW, 0 To MAX_COL)
For r = 0 To MAX_ROW
For c = 0 To MAX_COL
in_array(r, c) = CByte(m_InBoxes(r, c))
Next c
Next r
ReDim out_array(0 To (rmax - rmin + 1) * (cmax - cmin + _
1) - 1)
' Copy the data into out_array using MemCopy.
bytes_per_col = rmax - rmin + 1
idx = 0
For c = cmin To cmax
CopyMemory out_array(idx), in_array(rmin, c), _
bytes_per_col
idx = idx + bytes_per_col
Next c
' Display the results.
For r = txtOut.UBound + 1 To idx - 1
Load txtOut(r)
Set txtOut(r).Container = Frame1
txtOut(r).Move txtOut(r - 1).Left + txtOut(r - _
1).Width + 60, txtOut(r - 1).Top
Next r
For r = idx To txtOut.UBound
Unload txtOut(r)
Next r
For r = 0 To idx - 1
txtOut(r).Text = Format$(out_array(r))
txtOut(r).Visible = True
Next r
wid = txtOut(idx - 1).Left + txtOut(idx - 1).Width
If wid < cmdCopy.Left + cmdCopy.Width Then wid = _
cmdCopy.Left + cmdCopy.Width
Frame1.Width = wid + 120
Width = Frame1.Width + Width - ScaleWidth
End Sub
|
|
|
|
|
|