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?
Sure, that’s what
Marshal.Copyis 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.Copyuse would look like: