C # byte array with fixed pointer int

Is it possible to somehow indicate the type of pointer created by the fixed () operator?

In this situation:

I have an array of bytes that I would like to iterate through, but I would like the values ​​to be treated as int, thus having int * instead of byte *.

Here is a sample code:

byte[] rawdata = new byte[1024]; fixed(int* ptr = rawdata) //this fails with an implicit cast error { for(int i = idx; i < rawdata.Length; i++) { //do some work here } } 

Can this be done without having to do the throw inside the iteration?

+4
source share
3 answers
 byte[] rawdata = new byte[1024]; fixed(byte* bptr = rawdata) { int* ptr=(int*)bptr; for(int i = idx; i < rawdata.Length; i++) { //do some work here } } 
+4
source

I believe you need to go through byte* . For instance:

 using System; class Test { unsafe static void Main() { byte[] rawData = new byte[1024]; rawData[0] = 1; rawData[1] = 2; fixed (byte* bytePtr = rawData) { int* intPtr = (int*) bytePtr; Console.WriteLine(intPtr[0]); // Prints 513 on my box } } } 

Note that during iteration, you should use rawData.Length / 4 , not rawData.Length if you are treating your byte array as a sequence of 32-bit values.

+5
source

I found a - apparently - a more elegant and for some reason also faster way to do this:

  byte[] rawData = new byte[1024]; GCHandle rawDataHandle = GCHandle.Alloc(rawData, GCHandleType.Pinned); int* iPtr = (int*)rawDataHandle.AddrOfPinnedObject().ToPointer(); int length = rawData.Length / sizeof (int); for (int idx = 0; idx < length; idx++, iPtr++) { (*iPtr) = idx; Console.WriteLine("Value of integer at pointer position: {0}", (*iPtr)); } rawDataHandle.Free(); 

Thus, the only thing I need to do - besides setting the correct iteration length - is to increase the pointer. I compared the code to the one that uses the fixed operator, and this one is a bit faster.

+2
source

Source: https://habr.com/ru/post/1391419/


All Articles