C# 如何从 IntPtr 获取 Byte[]
我有一个具有委托的 .dll(不是我自己的)。这个委托回调函数是:
"CallBackFN(ushort opCOde, IntPtr Payload, uint size, uint localIP)"
如何将 IntPtr 转换为 Byte[]?我认为有效负载实际上是Byte[]。如果它不是 Byte[] 并且是其他东西,我会丢失一些数据吗?
I have a .dll(not my own) that has a delegate. This delegate Callback function is:
"CallBackFN(ushort opCOde, IntPtr payload, uint size, uint localIP)"
How can i convert IntPtr to Byte[]? I think that payload is actually Byte[]. If it's not Byte[] and it's something else would i lose some data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果是
byte[]
数组:如果不是
byte[]
,则Marshal.Copy中的size参数是数组中元素的个数,而不是字节大小。因此,如果您有一个int[]
数组而不是byte[]
数组,则必须除以 4(每个 int 的字节数)才能获得正确的数量要复制的元素,假设通过回调传递的大小参数指的是字节数。If it's a
byte[]
array:If it's not
byte[]
, the size parameter in of Marshal.Copy is the number of elements in the array, not the byte size. So, if you had anint[]
array rather than abyte[]
array, you would have to divide by 4 (bytes per int) to get the correct number of elements to copy, assuming your size parameter passed through the callback refers to the number of bytes.如果需要性能,直接使用:
If you need performance, use it directly:
你研究过 Marshal.Copy 了吗?
http://msdn.microsoft.com/en-us/library/ system.runtime.interopservices.marshal.copy.aspx
Have you looked into Marshal.Copy?
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.copy.aspx
根据这个Stack Overflow问题,您可以执行以下操作:
According to this Stack Overflow question, you can do the following:
Span
可能是一个更好的解决方案,因为它提供了字节数组所需的大多数功能。它更快,因为您不需要分配和复制到新的缓冲区,并且更安全,因为您不必直接使用指针。它包含在 .NET Core 2.1 和用于 . NET Framework 4.5 + 和 .NET Core 2.0 +;
Span<byte>
may be a better solution as it provides most features you need from a byte array. It is faster as you won't need to allocate and copy to a new buffer and safer as you will not have to use directly the pointer.It's included in.NET Core 2.1 and a nuget package (System.Memory) for .NET Framework 4.5 + and .NET Core 2.0 +;
您可以使用 Marshal.Copy 方法(IntPtr、Byte[]、Int32、Int32)< /a>
You can use Marshal.Copy Method (IntPtr, Byte[], Int32, Int32)