When i try to read the memory size of my structure i get the Exception:
"File I/O of a structure with field 'cbSize' of type 'UInt16' is not valid."
My structure:
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)>
Public Structure MyStructure
Public V1 As UInt16
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=30)> _
Public V2 As String
Public V3 As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=256)> _
Public V4 As String
Public V5 As Byte
Public V6 As Byte
Public V7 As UInt16
Public V8 As UInt16
Public V9 As UInt16
Public V10 As Integer
Public V11 As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=8)> _
Public V12 As String
End Structure
I wrote a function which counts the value of each Len(Vxx). This function works, but im getting the wrong value...
size = Len(V1) + Len(V2) + Len(V3) ....
When i change the value Type to Int16 there are no problems with Len(structure).
Now my question: Why it doesn't work with UInt16?
And
Is there any way how i can use UInt16 and get the right value from Len()?
Thank you for your suggestions.
Use Marshal.SizeOf() like this:
Dim ms As New MyStructure
' ... populate "ms" ...
Dim sz As Integer = Marshal.SizeOf(ms)