从固定对象获取字节数组 [英] getting a byte array from a pinned object

查看:55
本文介绍了从固定对象获取字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以从托管数组中获取指针

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?

推荐答案

当然,这就是 Marshal.Copy 的用途 - 没有办法(好吧,没有办法不复制某些种类)否则在托管和非托管状态之间获取内存......好吧,这不是 100% 正确,但我假设您不想仅仅依赖 Win32/C 和 p/invoke 来复制内存.

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 使用看起来像:

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

这篇关于从固定对象获取字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆