getting a byte array from a pinned object

2019-08-07 09:29发布

问题:

It is possible to get a pointer from a managed array

byte [] buffer = new byte[length + byteAlignment];
GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr  ptr = bufferHandle.AddrOfPinnedObject();

is there any way to do the opposite. getting a byte array from a pinned object without copying?

回答1:

Sure, that's what Marshal.Copy is for - there is no way (well, no way without copying of some variety) to otherwise get memory between the managed and unmanaged states...well, that's not 100% true, but I'm assuming you don't want to rely solely on Win32/C and p/invoke to copy memory around.

Marshal.Copy use would look like:

IntPtr addressOfThing = ....;
byte[] buffer = new byte[...];
Marshal.Copy(addressOfThing, buffer, 0, bufferSize);