Hi Mattias
Well spotted. I have converted it and tried it succesfully. It is certainly
shorter and quicker than the reflection route, but perhaps less flexible.
The latter makes it possible to code for big endian and little endian,
whereas the former simply does a byte for byte copy.
I will keep both up my sleeve I think.
For completeness, I have included both solutions below.
<reflection>
Imports System.Reflection
Public Class Struct
Public Shared Function Convert(ByVal MyStruct As Object) As Byte()
Dim al As ArrayList
Dim Fields As FieldInfo() = MyStruct.GetType.GetFields
al = New ArrayList
For Each fld As FieldInfo In Fields
If fld.FieldType.Equals(GetType(Byte)) Then
' Add byte to array list
al.Add(CByte(fld.GetValue(MyStruct)))
ElseIf fld.FieldType.Equals(GetType(Int16)) Then
' Add 16-bit value to array list
Dim i16 As Int16
i16 = CType(fld.GetValue(MyStruct), Int16)
al.Add(CByte(i16 >> 8))
al.Add(CByte(i16 And &HFF))
Else
Throw New Exception("Cannot convert type.")
End If
Next fld
Return DirectCast(al.ToArray(GetType(Byte)), Byte())
End Function
End Class
</reflection>
<memcopy>
Public Function RawSerialize(ByVal anything As Object) As Byte()
Dim rawsize As Integer = Marshal.SizeOf(anything)
Dim buffer As IntPtr = Marshal.AllocHGlobal(rawsize)
Marshal.StructureToPtr(anything, buffer, False)
Dim rawdatas(rawsize - 1) As Byte
Marshal.Copy(buffer, rawdatas, 0, rawsize)
Marshal.FreeHGlobal(buffer)
Return rawdatas
End Function
Public Function RawDeserialize(ByVal rawdatas As Byte(), ByVal anytype As
Type) As Object
Dim rawsize As Integer = Marshal.SizeOf(anytype)
If (rawsize > rawdatas.Length) Then
Return Nothing
End If
Dim buffer As IntPtr = Marshal.AllocHGlobal(rawsize)
Marshal.Copy(rawdatas, 0, buffer, rawsize)
Dim retobj As Object = Marshal.PtrToStructure(buffer, anytype)
Marshal.FreeHGlobal(buffer)
Return retobj
End Function
</memcopy>
Cheers
Charles
"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:uj**************@TK2MSFTNGP09.phx.gbl...
Charles,
Check out
http://groups.google.com/groups?selm...%40tkmsftngp05
It's C# code, but shouldn't be too hard to translate to VB.
Mattias
--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.