7,763
社区成员
发帖
与我相关
我的任务
分享
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Integer)
Public Type tabdata
id As Long
name As String
nr As String
flag As Long
End Type
Public Function ToBytes(ByRef obj As tabdata) As Byte()
Dim n As Integer
Dim i As Integer
Dim j As Integer
Dim bstrName() As Byte
bstrName = obj.name
Dim nameLen As Integer
nameLen = UBound(bstrName) + 1
Dim bstrNr() As Byte
bstrNr = obj.nr
Dim nrLen As Integer
nrLen = UBound(bstrNr) + 1
n = Len(obj.id) + Len(obj.flag) + nameLen + nrLen + 4 '2个字节保存字符串长度,假设最长65535个如果觉得不够你再改
ReDim result(0 To n - 1) As Byte
CopyMemory ByVal VarPtr(result(0)), obj.id, Len(obj.id)
i = Len(obj.id)
CopyMemory ByVal VarPtr(result(i)), obj.flag, Len(obj.flag)
i = i + Len(obj.flag)
CopyMemory ByVal VarPtr(result(i)), nameLen, Len(nameLen)
i = i + Len(nameLen)
For j = 0 To UBound(bstrName)
result(j + i) = bstrName(j)
Next
i = i + nameLen
CopyMemory ByVal VarPtr(result(i)), nrLen, Len(nrLen)
i = i + Len(nrLen)
For j = 0 To UBound(bstrNr)
result(j + i) = bstrNr(j)
Next
ToBytes = result
End Function
Public Function FromBytes(ByRef data() As Byte) As tabdata
Dim i As Integer
Dim t As Integer
Dim obj As tabdata
CopyMemory obj.id, ByVal VarPtr(data(0)), Len(obj.id)
i = Len(obj.id)
CopyMemory obj.flag, ByVal VarPtr(data(i)), Len(obj.flag)
i = i + Len(obj.flag)
CopyMemory ByVal VarPtr(t), ByVal VarPtr(data(i)), Len(t)
i = i + Len(t)
ReDim tempstr(0 To t - 1) As Byte
For n = 0 To UBound(tempstr)
tempstr(n) = data(i + n)
Next
obj.name = tempstr
i = i + t
CopyMemory ByVal VarPtr(t), ByVal VarPtr(data(i)), Len(t)
i = i + Len(t)
ReDim tempstr(0 To t - 1) As Byte
For n = 0 To UBound(tempstr)
tempstr(n) = data(i + n)
Next
obj.nr = tempstr
FromBytes = obj
End Function
Private Sub Command1_Click()
Dim obj As tabdata '声明type对象
'赋值
With obj
.flag = 123
.id = 456
.name = "test"
.nr = "csdn"
End With
Dim b() As Byte
b = ToBytes(obj)
Dim dest_obj As tabdata
dest_obj = FromBytes(b)
MsgBox dest_obj.nr + vbCrLf + dest_obj.name
End Sub
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Integer)
Public Type tabdata
id As Long
name As String * 24'需要指定长度的
nr As String * 24'需要指定长度的
flag As Long
End Type
Private Sub Command1_Click()
Dim obj As tabdata '声明type对象
'赋值
With obj
.flag = 123
.id = 456
.name = "test"
.nr = "csdn"
End With
'声明字节数组
Dim temp(Len(obj) - 1) As Byte
'把对象复制到字节数组中
CopyMemory ByVal VarPtr(temp(0)), obj, Len(obj)
'定义另一个tabtype对象
Dim dest_obj As tabdata
CopyMemory dest_obj, ByVal VarPtr(temp(0)), Len(obj)
MsgBox dest_obj.nr
End Sub