Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 753405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T14:53:36+00:00 2026-05-14T14:53:36+00:00

I have a system where a remote agent sends serialized structures (from an embedded

  • 0

I have a system where a remote agent sends serialized structures (from an embedded C system) for me to read and store via IP/UDP. In some cases I need to send back the same structure types. I thought I had a nice setup using Marshal.PtrToStructure (receive) and Marshal.StructureToPtr (send). However, a small gotcha is that the network big endian integers need to be converted to my x86 little endian format to be used locally. When I’m sending them off again, big endian is the way to go.

Here are the functions in question:

    private static T BytesToStruct<T>(ref byte[] rawData) where T: struct
    {
        T result = default(T);
        GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
        try
        {
            IntPtr rawDataPtr = handle.AddrOfPinnedObject();
            result = (T)Marshal.PtrToStructure(rawDataPtr, typeof(T));
        }
        finally
        {
            handle.Free();
        }
        return result;
    }

    private static byte[] StructToBytes<T>(T data) where T: struct
    {
        byte[] rawData = new byte[Marshal.SizeOf(data)];
        GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
        try
        {
            IntPtr rawDataPtr = handle.AddrOfPinnedObject();
            Marshal.StructureToPtr(data, rawDataPtr, false);
        }
        finally
        {
            handle.Free();
        }
        return rawData;
    }

And a quick example structure that might be used like this:

byte[] data = this.sock.Receive(ref this.ipep);
Request request = BytesToStruct<Request>(ref data);

Where the structure in question looks like:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
private struct Request
{
    public byte type;
    public short sequence;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
    public byte[] address;
}

What (generic) way can I swap the endianness when marshalling the structures? My need is such that the locally stored ‘request.sequence’ in this example should be little-endian for displaying to the user. I don’t want to have to swap the endianness in a structure-specific way since it’s a generic problem.

My first thought was to use Reflection, but I’m not very familiar with that feature. Also, I hoped that there would be a better solution out there that somebody could point me towards. Thanks in advance 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T14:53:36+00:00Added an answer on May 14, 2026 at 2:53 pm

    Reflection does seem like the only real way to accomplish what you’re after.

    I’ve put together some code below. It creates an attribute called EndianAttribute that can be applied at the field level on a struct. I’ve included the definition for this attribute and it’s associated enum, as well as the modifications to your code necessary to use it.

    As a side note, you did not need to define rawData as a ref parameter.

    Note that this does require the use of C# 3.0/.NET 3.5, since I’m using LINQ and anonymous types in the function doing the work. It would not be difficult to rewrite the function without these features, though.

    [AttributeUsage(AttributeTargets.Field)]
    public class EndianAttribute : Attribute
    {
        public Endianness Endianness { get; private set; }
    
        public EndianAttribute(Endianness endianness)
        {
            this.Endianness = endianness;
        }
    }
    
    public enum Endianness
    {
        BigEndian,
        LittleEndian
    }
    
    private static void RespectEndianness(Type type, byte[] data)
    {
        var fields = type.GetFields().Where(f => f.IsDefined(typeof(EndianAttribute), false))
            .Select(f => new
            {
                Field = f,
                Attribute = (EndianAttribute)f.GetCustomAttributes(typeof(EndianAttribute), false)[0],
                Offset = Marshal.OffsetOf(type, f.Name).ToInt32()
            }).ToList();
    
        foreach (var field in fields)
        {
            if ((field.Attribute.Endianness == Endianness.BigEndian && BitConverter.IsLittleEndian) ||
                (field.Attribute.Endianness == Endianness.LittleEndian && !BitConverter.IsLittleEndian))
            {
                Array.Reverse(data, field.Offset, Marshal.SizeOf(field.Field.FieldType));
            }
        }
    }
    
    private static T BytesToStruct<T>(byte[] rawData) where T : struct
    {
        T result = default(T);
    
        RespectEndianness(typeof(T), rawData);     
    
        GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
    
        try
        {
            IntPtr rawDataPtr = handle.AddrOfPinnedObject();
            result = (T)Marshal.PtrToStructure(rawDataPtr, typeof(T));
        }
        finally
        {
            handle.Free();
        }        
    
        return result;
    }
    
    private static byte[] StructToBytes<T>(T data) where T : struct
    {
        byte[] rawData = new byte[Marshal.SizeOf(data)];
        GCHandle handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
        try
        {
            IntPtr rawDataPtr = handle.AddrOfPinnedObject();
            Marshal.StructureToPtr(data, rawDataPtr, false);
        }
        finally
        {
            handle.Free();
        }
    
        RespectEndianness(typeof(T), rawData);     
    
        return rawData;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 387k
  • Answers 387k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Step 1. download image Step 2. Run image through simple… May 14, 2026 at 11:59 pm
  • Editorial Team
    Editorial Team added an answer You need to add the elements in output.config to the… May 14, 2026 at 11:59 pm
  • Editorial Team
    Editorial Team added an answer LINQ? var item = sequence.Where(x => x.Age > 100) .Select(x… May 14, 2026 at 11:59 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.