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[].
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.
The Marshal class could help you.
byte[] bytes = new byte[length]; for(int i = 0; i < length; ++i) bytes[i] = Marshal.ReadByte(yourPtr, i);
I think you might use Marshal.Copy too.