何时在 WriteFile() 和 ReadFile() 中使用托管内存与非托管内存

发布于 2024-12-27 07:58:36 字数 780 浏览 1 评论 0原文

我从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北方。的韩爷 2025-01-03 07:58:36

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文