何时在 WriteFile() 和 ReadFile() 中使用托管内存与非托管内存
我从 www.lvr.com 获得了一些示例代码,展示了如何使用 WriteFile() 和 ReadFile() 从 USB 设备写入/读取。在示例中,Jan 使用非托管内存作为 WriteFile() 和 ReadFile() 的参数。然而,似乎这些函数只需传递托管内存等价物就可以正常工作。
Public managedOverlapped As System.Threading.NativeOverlapped
Public nonManagedOverlapped As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(managedOverlapped))
Marshal.StructureToPtr(managedOverlapped, nonManagedOverlapped, False)
Public managedBuffer(64) As Byte
Public nonManagedBuffer As IntPtr = Marshal.AllocHGlobal(64)
api_status = ReadFile(readHandle, nonManagedBuffer, 64, BytesSucceed, nonManagedOverlapped)
效果同样好:
api_status = ReadFile(readHandle, managedBuffer, 64, BytesSucceed, managedOverlapped)
何时需要在 WriteFile / ReadFile 中或在 .Net 中使用非托管内存?
I got some example code from www.lvr.com showing how to use WriteFile() and ReadFile() to write/read from a USB device. In the example, Jan uses unmanaged memory as parameters to WriteFile() and ReadFile(). However, it seems that the functions work fine just passing the managed memory equivalents.
Public managedOverlapped As System.Threading.NativeOverlapped
Public nonManagedOverlapped As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(managedOverlapped))
Marshal.StructureToPtr(managedOverlapped, nonManagedOverlapped, False)
Public managedBuffer(64) As Byte
Public nonManagedBuffer As IntPtr = Marshal.AllocHGlobal(64)
api_status = ReadFile(readHandle, nonManagedBuffer, 64, BytesSucceed, nonManagedOverlapped)
works just as well as:
api_status = ReadFile(readHandle, managedBuffer, 64, BytesSucceed, managedOverlapped)
When is it necessary to use unmanaged memory in WriteFile / ReadFile or in general in .Net?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Blittable 类型(如 Byte)在传递给本机函数时简单地固定到位。 (参考:http://msdn.microsoft.com/en-us/library/ 75dwhxf7.aspx)
如果参数不是 blittable 类型,则将在调用的生命周期内创建对象的副本。对于较大的分配来说,这可能会很昂贵,因此您可以(自行决定)直接分配非托管内存并将其传递给该方法。
Blittable types (like Byte) are simply pinned in-place when passed to a native function. (Ref: http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx)
If the parameter was not a blittable type, a copy of the object would be made for the lifetime of the call. This can be expensive for larger allocations, so you can (at your discretion) allocate unmanaged memory directly and pass it to the method.