Problem:
I have a struct of a fixed size that I’m trying to marshal. This struct contains a number of useful fields for the current version of the struct and a specified amount of unused space at the end that is reserved for future modifications.
How should I design this structure so that the size of the reserved space will be automatically updated when I modify the structure?
While the following would solve my problem
'Variable size structure
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Structure UsefulData
Dim foo As SByte
Dim bar As Integer
Dim foobar As Short
End Structure
Const MAX_SIZE As Integer = 20
'Fixed size structure
<StructLayout(LayoutKind.Sequential, Pack:=1, Size:=MAX_SIZE>
Structure Data
Dim current As UsefulData
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=MAX_SIZE-System.Runtime.InteropServices.Marshal.SizeOf(GetType(UsefulData)))>
Dim reserved As SByte()
End Structure
but doesn’t compile as System.Runtime.InteropServices.Marshal.SizeOf(GetType(UsefulData)) is not a constant expression. Any ideas?
Upon further reflection on this problem I’ve come to question the validity of my desire to expose the reserved space at the end of the struct. In reality nothing should ever reference the reserved section. If something ever needed to, then the correct approach would be to modify the structure itself to expose the relevant parts of the reserved space.
Consequently the structure should look as follows: