Deserializing numerics from big endian problem (advanced topic)

  • Thread starter Thread starter Thomas
  • Start date Start date
T

Thomas

Hello developers,

I have a problem deserializing structures containing numeric data stored in
big endian format using framework Marshal.PtrToStructure() method. There
must be any attribute I can use to specify that MyStruct.Size attribute
(code sample below) is stored as big endian as opposed to default little
endian. I spend two hours gooling and found nothing useful.

I know byte order can be convert in code, but I was wondering if there was
any way of handling it automatically.

Thank you for any pointers.

Thomas

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
struct MyStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string Name;
[MarshalAs(UnmanagedType.U4)]
public uint Size;
}
 
Peter Duniho said:
I'm not sure what you mean by "there must be". That phrase would normally
be a statement that the only possibility is that such support exists.
But, as far as I know, there is no such requirement, nor is there any such
support in .NET.

I guess, the phrase was rhetorical.

Thomas
 
Thomas said:
I have a problem deserializing structures containing numeric data stored
in big endian format using framework Marshal.PtrToStructure() method.
There must be any attribute I can use to specify that MyStruct.Size
attribute (code sample below) is stored as big endian as opposed to
default little endian. I spend two hours gooling and found nothing useful.

I know byte order can be convert in code, but I was wondering if there
was any way of handling it automatically.
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
struct MyStruct
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public string Name;
[MarshalAs(UnmanagedType.U4)]
public uint Size;
}

No. Because the point in StructLayout is to match native memory
layout. Native memory layout uses little endian integers on x86.

You need to convert manually (IPAddress.NetworkToHostOrder can do
the byte moving).

Arne
 
Back
Top