21

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

5
  • shouldn'y byte[] be const byte* by default? so try indexing the pointer as *(myByte+index); But i guess it if were that easy you wouldn't be asking.... Commented Jul 10, 2013 at 11:27
  • You should be able to write *(myByte+index) as myByte[index]. No conversion necessary. Commented Jul 10, 2013 at 11:29
  • @HenkHolterman I must convert it to byte[] because I have to pass it to the constructor of IPAddress. Commented Jul 10, 2013 at 11:33
  • But do you need safe (managed) byte[] or not? Commented Jul 10, 2013 at 11:34
  • @HenkHolterman The IPAddress ctor needs a safe/managed byte[]: msdn.microsoft.com/en-us/library/t4k07yby.aspx Commented Jul 10, 2013 at 11:37

2 Answers 2

25

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.

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

10 Comments

This looks good, I was gonna suggest traversing the pointed-to array and filling by hand, or memcpy, but this seems like a C# way of doing it. (y)
This question is a follow-up to this one: stackoverflow.com/questions/17549123/…
I'd err towards IntPtr and Marshal.Copy if I were you.
Thank you, David, I didn't know that an unsafe pointer can be casted to IntPtr.
"I'd err towards IntPtr and Marshal.Copy if I were you." - Why? I would also like to know your opinion on my other question (pls. check out the link if you have time). I haven't got any answers to that one, just some comments.
|
1

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.

1 Comment

Since this has to happen in an unsafe block, you don't need Marshal.ReadByte and you can just use good old fashioned pointer de-reference and pointer increment. That is if you wish to perform the copy in a loop rather than using Marshal.Copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.