Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from byte* to byte[]

Tags:

c#

How do I convert a pointer to a byte array?

The first byte indicates the number of bytes to follow.

like image 442
Robert Avatar asked Dec 29 '22 10:12

Robert


2 Answers

The safe thing to do is to make a copy of the data pointed to.

If you have a byte* then you can of course just write the code yourself:

byte* source = whatever;
int size = source[0]; // first byte is size;
byte[] target = new byte[size];
for (int i = 0; i < size; ++i)
    target[i] = source[i+1];

Easy peasy.

If instead of a byte* you have an IntPtr then you can use this helpful method:

http://msdn.microsoft.com/en-us/library/ms146631.aspx

There are lots of helpful methods on the Marshal class.

like image 182
Eric Lippert Avatar answered Dec 30 '22 23:12

Eric Lippert


Well, the byte* isn't the array object. You can get the address of the data (using fixed etc), but an arbitrary byte* does not have to be the start of the data - it could be at offset 17, for example.

So I would recommend either:

  • pass the byte[] around instead
  • (or) create a new byte[] and copy over the data you want
like image 32
Marc Gravell Avatar answered Dec 31 '22 00:12

Marc Gravell