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 6672493
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T03:30:54+00:00 2026-05-26T03:30:54+00:00

Using .NET 4.0 I can quickly convert a struct to and from an array

  • 0

Using .NET 4.0 I can quickly convert a struct to and from an array of bytes by making use of the Marshal class. For example, the following simple example will run at around 1 million times per second on my machine which is fast enough for my purposes…

    [StructLayout(LayoutKind.Sequential)]
    public struct ExampleStruct
    {
        int i1;
        int i2;
    }

    public byte[] StructToBytes()
    {
        ExampleStruct inst = new ExampleStruct();

        int len = Marshal.SizeOf(inst);
        byte[] arr = new byte[len];
        IntPtr ptr = Marshal.AllocHGlobal(len);
        Marshal.StructureToPtr(inst, ptr, true);
        Marshal.Copy(ptr, arr, 0, len);
        Marshal.FreeHGlobal(ptr);

        return arr;
    }

But the Marshal class is not available under WinRT, which is reasonable enough for security reasons, but it means I need another way to achieve my struct to/from byte array.

I am looking for an approach that works for any fixed size struct. I could solve the problem by writing custom code for each struct that knows how to convert that particular struct to and form a byte array but that is rather tedious and I cannot help but feel there is some generic solution.

  • 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-26T03:30:54+00:00Added an answer on May 26, 2026 at 3:30 am

    One approach would be a combination of Expressions and Reflection (I’ll leave caching as an implementation detail):

    // Action for a given struct that writes each field to a BinaryWriter
    static Action<BinaryWriter, T> CreateWriter<T>()
    {
        // TODO: cache/validate T is a "simple" struct
    
        var bw = Expression.Parameter(typeof(BinaryWriter), "bw");
        var obj = Expression.Parameter(typeof(T), "value");
    
        // I could not determine if .Net for Metro had BlockExpression or not
        // and if it does not you'll need a shim that returns a dummy value
        // to compose with addition or boolean operations
        var body = Expression.Block(
           from f in typeof(T).GetTypeInfo().DeclaredFields
           select Expression.Call(
               bw,
               "Write",
               Type.EmptyTypes, // Not a generic method
               new[] { Expression.Field(obj, f.Name) }));
    
        var action = Expression.Lambda<Action<BinaryWriter, T>>(
            body,
            new[] { bw, obj });
    
        return action.Compile();
    }
    

    Used like so:

    public static byte[] GetBytes<T>(T value)
    {
        // TODO: validation and caching as necessary
        var writer = CreateWriter(value);
        var memory = new MemoryStream();
        writer(new BinaryWriter(memory), value);
        return memory.ToArray();
    }
    

    To read this back, it is a bit more involved:

    static MethodInfo[] readers = typeof(BinaryReader).GetTypeInfo()
        .DeclaredMethods
        .Where(m => m.Name.StartsWith("Read") && !m.GetParameters().Any())
        .ToArray();
    
    // Action for a given struct that reads each field from a BinaryReader
    static Func<BinaryReader, T> CreateReader<T>()
    {
        // TODO: cache/validate T is a "simple" struct
    
        var br = Expression.Parameter(typeof(BinaryReader), "br");
    
        var info = typeof(T).GetTypeInfo();
    
        var body = Expression.MemberInit(
           Expression.New(typeof(T)),
           from f in info.DeclaredFields
           select Expression.Bind(
               f,
               Expression.Call(
                   br,
                   readers.Single(m => m.ReturnType == f.FieldType),
                   Type.EmptyTypes, // Not a generic method
                   new Expression[0]));
    
        var function = Expression.Lambda<Func<BinaryReader, T>>(
            body,
            new[] { br });
    
        return function.Compile();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

ASP.NET MVC can generate HTML elements using HTML Helpers, for example @Html.ActionLink() , @Html.BeginForm()
Using .Net (C#), how can you work with USB devices? How can you detect
When using .NET's WebBrowser control, how can I get the entire HTML of the
How can I modify the PDF document properties programmatically using .NET code? I have
How can I create a local user account using .NET 2.0 and c# and
How can I monitor instant messages received on gtalk using .NET? Basically, I need
I'm using .net. Is there some code somewhere that can change $11,456.50 -> eleven
I am building a web site in C# using asp.NET MVC How can I
.NET: How can I copy the files using Windows Copy Files dialog. I need
Using WPF .NET 4.0 in VS2010 RTM: I can't create a fullscreen WPF popup.

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.