简体   繁体   中英

Marshal copying struct to byte array comes out as 0 for each byte

I have a method which takes a type and converts it into a byte array. But for some reason the byte array result always ends up with 0 in each index.

I don't know why this is happening, i am passing my own struct which does have values set, i am checking for that, so i shouldn't be getting 0 for every index.

This is my method to convert to a byte array:

    public static bool TryGetBytes<T>(T obj, ref byte[] arr)
    {
        int size = Marshal.SizeOf(obj);
        if (size > arr.Length)
        {
            Debug.Log("Size error!" + size + " : "+arr.Length);
            return false;
        }

        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(obj, ptr, true);
        Marshal.Copy(ptr, arr, size, 0);
        Marshal.FreeHGlobal(ptr);
        return true;
    }

Is there anything i might be doing wrong here? Do i need ref at all ? I tried without ref and no difference occurred. So i am a bit confused how to get this to work.

Your error in the use of Marshal.Copy: https://msdn.microsoft.com/en-us/library/ms146631(v=vs.110).aspx

 public static void Copy(
    IntPtr source,
     byte[] destination,
     int startIndex,
     int length
 ) 

You've got the start index and length reversed. I'm guessing it doesn't throw an exception because length is 0.

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