Well, the main idea that I'm trying to do is convert a byte array into something like a short or integer, etc. etc.
A simple example would be:
unsafe { fixed (byte* byteArray = new byte[5] { 255, 255, 255, 126, 34 }) { short shortSingle = *(short*)byteArray; MessageBox.Show((shortSingle).ToString()); // works fine output is -1 } }
Okay, so what I'm really trying to do is make an extension for the Stream class; advanced read and write methods. I need help with the following code:
unsafe public static T Read<T>(this Stream stream) { int bytesToRead = sizeof(T); // ERROR: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') byte[] buffer = new byte[bytesToRead]; if (bytesToRead != stream.Read(buffer, 0, bytesToRead)) { throw new Exception(); } fixed (byte* byteArray = buffer) { T typeSingle = *(T*)byteArray; // ERROR: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') return typeSingle; } } unsafe public static T[] Read<T>(this Stream stream, int count) { // haven't figured out it yet. This is where I read and return T arrays }
It seems to me that I should use pointers for speed, because I will work on writing and reading data from streams, such as NetworkStream classes. Thank you for your help!
EDIT:
And although I am trying to figure out how to return T-arrays, I ran into this problem:
unsafe { fixed (byte* byteArray = new byte[5] { 0, 0, 255, 255, 34 }) { short* shortArray = (short*)byteArray; MessageBox.Show((shortArray[0]).ToString()); // works fine output is 0 MessageBox.Show((shortArray[1]).ToString()); // works fine output is -1 short[] managedShortArray = new short[2]; managedShortArray = shortArray; // The problem is, How may I convert pointer to a managed short array? ERROR: Cannot implicitly convert type 'short*' to 'short[]' } }
SUMMARY: I need to convert from a byte array to a given type T OR a given type of array T with a given length
c #
haxxoromer
source share