问一个很基础的问题--关于UDT结构转换字节数组
最近碰到一个udt结构转换成字节数组的问题。如果udt结构体内只有Integer和Long类型,测试代码好像可以的。但是如果结构体内有Byte或字符串类型,则转换成字节数组后会有出入。这个怎么解决?
Private Type tUDT ''11 bytes?
sW As Integer
sH As Integer
A As Long
' b As String * 5
sd1 As Byte
' sd2 As Byte
' sd3 As Byte
End Type
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Sub WriteTofiles()
On Error Resume Next
Dim i As Long, budt As tUDT, w1 As String
i = FreeFile()
w1 = "d:\tmp0.dat"
Kill w1
Open w1 For Binary Access Write As #i
With budt
.sW = 100
.sH = 200
.A = 10000
' .b = "abcde"
.sd1 = 35
' .sd2 = 205
' .sd3 = 255
End With
'''直接写入udt结构
Put #i, , budt
Put #i, , "End" '''写入分隔符区别前后2段
''''测试将udt结构转换成字节数组后再写入
Dim byt() As Byte
ReDim byt(Len(budt) - 1)
CopyMemory ByVal VarPtr(byt(0)), ByVal VarPtr(budt), Len(budt)
Put #i, , byt
Close #i
'''''
End Sub
Option Explicit
Private Type tUDT ''16 bytes
sW As Integer
sH As Integer
A As Long
b As String * 5
sd1 As Byte
sd2 As Byte
sd3 As Byte
End Type
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Sub Command1_Click()
Dim budt As tUDT
Dim bits() As Byte
ReDim bits(Len(budt) - 1)
With budt
.sW = 100
.sH = 200
.A = 10000
.b = "abcde"
.sd1 = 35
.sd2 = 205
.sd3 = 255
End With
Call CopyMemory(bits(0), budt, Len(budt))
Debug.Print bits(13)
Debug.Print bits(14)
Debug.Print bits(15)
Dim vTex As String * 5
Dim vBuf() As Byte
ReDim vBuf(4)
Call CopyMemory(vBuf(0), bits(8), 5)
Debug.Print StrConv(vBuf, vbUnicode)
End Sub