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

  • Home
  • SEARCH
  • 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 189729
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T16:11:49+00:00 2026-05-11T16:11:49+00:00

I have a Read generic function that does its job very well. It reads

  • 0

I have a Read generic function that does its job very well. It reads from a buffer of bytes and returns the specific type

public static T Read<T>()
{
    // An T[] would be a reference type, and a lot easier to work with.
    T[] t = new T[1];

    // Marshal.SizeOf will fail with types of unknown size. Try and see...
    int s = Marshal.SizeOf(typeof(T));
    if (index + s > size)
        // Should throw something more specific.
        throw new Exception("Error 101 Celebrity");

    // Grab a handle of the array we just created, pin it to avoid the gc
    // from moving it, then copy bytes from our stream into the address
    // of our array.
    GCHandle handle = GCHandle.Alloc(t, GCHandleType.Pinned);
    Marshal.Copy(dataRead, index, handle.AddrOfPinnedObject(), s);

    index += s;

    // Return the first (and only) element in the array.
    return t[0];
}

Problem: How to do the Write function?

public static T Write<T>()
{
    // An T[] would be a reference type, and a lot easier to work with.
    T[] t = new T[1];

    // Marshal.SizeOf will fail with types of unknown size. Try and see...
    int s = Marshal.SizeOf(typeof(T));
    if (index + s > size)
        // Should throw something more specific.
        throw new Exception("Error 101 Celebrity");

    // Grab a handle of the array we just created, pin it to avoid the gc
    // from moving it, then copy bytes from our stream into the address
    // of our array.
    GCHandle handle = GCHandle.Alloc(dataWrite, GCHandleType.Pinned);
    Marshal.Copy(t, index, handle.AddrOfPinnedObject(), s); // ?? Problem

    index += s;
}

“t” should be byte[] array. How do I accomplish that?

  • 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-11T16:11:49+00:00Added an answer on May 11, 2026 at 4:11 pm

    It’s a lot of code to put on SO, but here y’go. There are a few overloads for Marshal.Copy that suit your needs.

    class Program
    {
        static void Main(string[] args)
        {
            TestStruct test = new TestStruct();
            test.Bar = 100;
            test.Foo = 200;
    
            using (MemoryStream ms = new MemoryStream())
            {
                using (ObjectStream os = new ObjectStream(ms, false))
                {
                    os.Write(test);
                }
                ms.Seek(0, SeekOrigin.Begin);
                Console.WriteLine(BitConverter.ToString(ms.ToArray()));
                using (ObjectStream os = new ObjectStream(ms, false))
                {
                    TestStruct result = os.Read<TestStruct>();
                    Console.WriteLine(result.Bar);
                    Console.WriteLine(result.Foo);
                }
            }
    
            Console.ReadLine();
        }
    }
    
    struct TestStruct
    {
        public int Foo;
        public int Bar;
    }
    
    class ObjectStream : Stream
    {
        private Stream _backing;
        private bool _ownsStream = true;
    
        public ObjectStream(Stream source)
            :this(source, true)
        {
        }
    
        public ObjectStream(Stream source, bool ownsStream)
        {
            if (source == null)
                throw new ArgumentNullException("source");
    
            _backing = source;
            _ownsStream = ownsStream;
        }
    
        public override bool CanRead
        {
            get
            {
                return _backing.CanRead;
            }
        }
    
        public override bool CanSeek
        {
            get
            {
                return _backing.CanSeek;
            }
        }
    
        public override bool CanWrite
        {
            get
            {
                return _backing.CanWrite;
            }
        }
    
        public override void Flush()
        {
            _backing.Flush();
        }
    
        public override long Length
        {
            get
            {
                return _backing.Length;
            }
        }
    
        public override long Position
        {
            get
            {
                return _backing.Position;
            }
            set
            {
                _backing.Position = value;
            }
        }
    
        public override int Read(byte[] buffer, int offset, int count)
        {
            return _backing.Read(buffer, offset, count);
        }
    
        public override long Seek(long offset, SeekOrigin origin)
        {
            return _backing.Seek(offset, origin);
        }
    
        public override void SetLength(long value)
        {
            _backing.SetLength(value);
        }
    
        public override void Write(byte[] buffer, int offset, int count)
        {
            _backing.Write(buffer, offset, count);
        }
    
        /// <summary>
        /// Writes a value type to the stream.
        /// </summary>
        /// <typeparam name="T">The type of value.</typeparam>
        /// <param name="value">The value.</param>
        /// <returns>The number of bytes written to the stream.</returns>
        public int Write<T>(T value)
        {
            // An T[] would be a reference type, and alot easier to work with.
            T[] t = new T[1];
            t[0] = value;
    
            // Marshal.SizeOf will fail with types of unknown size. Try and see...
            int s = Marshal.SizeOf(typeof(T));
            // Create a temp array.
            byte[] target = new byte[s];
    
            // Grab a handle of the array we just created, pin it to avoid the gc
            // from moving it, then copy bytes from our stream into the address
            // of our array.
            GCHandle handle = GCHandle.Alloc(t, GCHandleType.Pinned);
            Marshal.Copy(handle.AddrOfPinnedObject(), target, 0, s); // ?? Problem
    
            // Write to the stream.
            Write(target, 0, s);
    
            return s;
        }
    
        /// <summary>
        /// Reads a value type from the stream.
        /// </summary>
        /// <typeparam name="T">The type to read.</typeparam>
        /// <returns>The data read from the stream.</returns>
        public T Read<T>()
        {
            // An T[] would be a reference type, and alot easier to work with.
            T[] t = new T[1];
    
            // Marshal.SizeOf will fail with types of unknown size. Try and see...
            int s = Marshal.SizeOf(typeof(T));
            byte[] target = new byte[s];
    
            // Make sure there is enough data.
            if (Read(target, 0, s) != s)
                throw new InvalidDataException("Not enough data.");
    
            // Grab a handle of the array we just created, pin it to avoid the gc
            // from moving it, then copy bytes from our stream into the address
            // of our array.
            GCHandle handle = GCHandle.Alloc(t, GCHandleType.Pinned);
            Marshal.Copy(target, 0, handle.AddrOfPinnedObject(), s);
    
            // Return the first (and only) element in the array.
            return t[0];
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing && _ownsStream)
                _backing.Dispose();
            base.Dispose(disposing);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

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

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

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

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

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The statement is called MERGE. Look it up, I'm too… May 12, 2026 at 7:59 pm
  • Editorial Team
    Editorial Team added an answer I'd be pretty skeptical of non-ObjC languages on the iPhone.… May 12, 2026 at 7:59 pm
  • Editorial Team
    Editorial Team added an answer 1.8 lacks lookbehind, not lookahead! All you need is this:… May 12, 2026 at 7:59 pm

Related Questions

I'm having a problem where a collection of objects isn't being accessed correctly when
I have a Java program that runs many small simulations. It runs a genetic
I was writing a generic class to read RSS feed from various source and
I am trying to write a simple function for windows that answers the following

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.