C# - Convert unsafe byte* to byte[]

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

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[].

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!