简体   繁体   中英

C# - Convert unsafe byte* to byte[]

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.

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