C# - Convert unsafe byte* to byte[]

kol picture kol · Jul 10, 2013 · Viewed 24.3k times · Source

I have an unsafe byte* pointing to a native byte array of known length. How can I convert it to byte[]?

An unsafe sbyte* pointing to a zero-terminated native string can be converted to a C# string easily, because there is a conversion constructor for this purpose, but I can't find a simple way to convert byte* to byte[].

Answer

David Heffernan picture David Heffernan · Jul 10, 2013

If ptr is your unsafe pointer, and the array has length len, you can use Marshal.Copy like this:

byte[] arr = new byte[len];
Marshal.Copy((IntPtr)ptr, arr, 0, len);

But I do wonder how you came by an unsafe pointer to native memory. Do you really need unsafe here, or can you solve the problem by using IntPtr instead of an unsafe pointer? And if so then there's probably no need for unsafe code at all.