getting a byte array from a pinned object

心已入冬 提交于 2019-12-11 04:54:21

问题


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);


来源:https://stackoverflow.com/questions/14141172/getting-a-byte-array-from-a-pinned-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!