Search code examples
c#network-programmingserializationprotobuf-netobjectpool

C# Protobuf .NET Using Preexisting Byte Array


So I am working with Protobufs in .NET and I am trying to incorporate them with a buffer pool and AsyncSocketEventArgs pool. The buffer pool assigns sections of a huge byte array to the event args.

So, the problem, I can't figure out a way to have Protobufs serialize directly onto one of my buffers. Instead all methods appear to serialize onto there own buffers, which wastes time/memory... Any way to do what I'm looking for?

EDIT: I have created a proto scheme and I generate messages that contain deltas not entirely serialized classes, so I believe using the attributes/Serializer class won't help me. I want to write the bytes directly into one of my buffers. I believe MemoryStream, from what I have read will still just point to a created byte array, which will still waste a lot of time/memory.


Solution

  • Use a memory stream

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.IO;
    
    
    namespace ConsoleApplication1
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                Person person = new Person();
                XmlSerializer serializer = new XmlSerializer(typeof(Person));
                MemoryStream stream = new MemoryStream();
    
                serializer.Serialize(stream, person); 
            }
    
    
        }
        public class Person
        {
        }
    
    }
    ​