C# Marshal.Copy Intptr to 16 bit managed unsigned integer array

c#, marshalling

Solution

Using unsafe code:

public static unsafe void Copy(IntPtr ptrSource, ushort[] dest, uint elements) {
  fixed(ushort* ptrDest = &dest[0]) {
     CopyMemory((IntPtr)ptrDest, ptrSource, elements * 2);    // 2 bytes per element
  }
}

public static unsafe void Copy(ushort[] source, Intptr ptrDest, uint elements) {
  fixed(ushort* ptrSource = &source[0]) {
     CopyMemory(ptrDest, (Intptr)ptrSource, elements * 2);    // 2 bytes per element
  }
}

[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length);

Can be easily adapted to copy uint[] and ulong[] (adjust the number of bytes per element)

Problem

Why does C# Marshal.Copy routine does not have any overload for copying from unmanaged memory pointer to 16 bit managed unsigned integer array? ex: ``` Copy(IntPtr, Byte[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array. Copy(IntPtr, Char[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed character array. Copy(IntPtr, Double[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed double-precision floating-point number array. Copy(IntPtr, Int16[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed 16-bit signed integer array. Copy(IntPtr, Int32[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed 32-bit signed integer array. Copy(IntPtr, Int64[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed 64-bit signed integer array. Copy(IntPtr, IntPtr[], Int32, Int32) Copies data from an unmanaged memory pointer to a managed IntPtr array. Copy(IntPtr, Single[], Int32, Int32). Copies data from an unmanaged memory pointer to a managed single-precision floating-point number array. ``` If there is no marshalling alternative, how do I copy unmanaged ushort array to managed ushort array?

Original source

Related problems