1

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.

4
  • 1
    you definitely need the 'ref' otherwise the things you do inside your function that work on arr will be working on a local copy and won't result in any changes after the function completes. Commented Oct 6, 2017 at 6:07
  • Okay thanks for clarifying that part :) I thought that might be the case. Commented Oct 6, 2017 at 6:08
  • shouldn't it be - Marshal.Copy(ptr, arr, 0, size)...? Commented Oct 6, 2017 at 6:15
  • @MineR oh damn it thats embaressing ! That solved the problem :D Commented Oct 6, 2017 at 6:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup that fixed it, silly mistake ! Think i need a coffee break! Thanks !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.