Reading a byte from Intptr

I have a situation where I have Intptr, and I have my own structure, which consists of 4 bytes. I want to read 4 bytes from Intptr into this structure of mine. But I want to fill 4 bytes in the structure separately. sort of

mystruct obj = new mystruct ().

obj.byte2 = "read the byte from Myintptr"
obj.byte1 = "read the next byte from MyIntptr"

Is it possible?

one way could be that I read it all into a byte array, first using Marshal.copy (), and then I will do the second step of copying to obj. But they are curious that there is another way.

+3
source share
2 answers

Are you looking for something like this?

obj.byte1 = System.Runtime.InteropServices.Marshal.ReadByte(ip, 0);
obj.byte2 = System.Runtime.InteropServices.Marshal.ReadByte(ip, 1);
+6
source

IntPtr, ptr Int32 . (, IntPtr 8, 4 64- )

IntPtr ptr = ...;
int val = (int)ptr;
byte[] bytes = BitConverter.GetBytes(val);

byte b1 = (byte)(val >> 24);
byte b2 = (byte)(val >> 16);
byte b3 = (byte)(val >> 8);
byte b4 = (byte) val;
0

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


All Articles