1

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
tosa
  • 411
  • 1
  • 3
  • 23

1 Answers1

3

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.

Joe
  • 41,484
  • 20
  • 104
  • 125