简体   繁体   中英

Marshal class instance from and to byte array

I'm trying to marshal a class instance from and to byte array using these methods:

Marshal to byte array:

        public static byte[] MakeArrayFromCat(Cat cat)
        {
            var size = Marshal.SizeOf(typeof(Cat));
            var bytes = new byte[size];
            var ptr = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(cat, ptr, false);
            Marshal.Copy(ptr, bytes, 0, size);
            Marshal.FreeHGlobal(ptr);
            return bytes;
        }

Marshal to class instance:

 public static Cat MakeCatFromArray(byte[] b)
        {
            var size = b.Length;
            var bytes = new byte[size];
            var ptr = Marshal.AllocHGlobal(size);
            Marshal.Copy(bytes, 0, ptr, size);
            var cat = (Cat)Marshal.PtrToStructure(ptr, typeof(Cat));
            Marshal.FreeHGlobal(ptr);
            return cat;
        }

Here's my class:

 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public class Cat
    {
        
        public string Name { get; set; }
        public int Weight { get; set; }
        public int Age { get; set; }

        public Cat (string name, int age, int weight)
        {
            Name = name;
            Age = age;
            Weight = weight;
        }
    }

So when I run the presented methods the program throws MissingMethodException meaning that there's no constructor that takes no arguements. I get it on this line (in MakeCatFromArray method):

var cat = (Cat)Marshal.PtrToStructure(ptr, typeof(Cat));

I've tried to add a default constructor, but what I get from it doesn't live up to what I expect: It gives me an instance with all its properties empty, although I marshalled an instance with non-default values. Thus I've got two questions:

1.How do I do marshalling properly in this case? 2.Is there any better way of converting an instance of a class into byte array without marking it as [Serializable] ?

The problem is with this:

Marshal.Copy(bytes, 0, ptr, size);

You are trying to create Cat from empty bytes array.

There should be b instead of bytes :

Marshal.Copy(b, 0, ptr, size);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM