2014-01-07 161 views
3

爲什麼C#Marshal.Copy例程沒有任何過載從非託管內存指針複製到16位管理無符號整數數組?C#Marshal.Copy Intptr到16位管理無符號整數數組

例如:

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. 

如果沒有編組的替代,如何複製非託管USHORT陣列管理USHORT陣列?

回答

-1

可能是因爲並非所有託管語言都有無符號類型。我不認爲這是一個很好的理由,但這是一個合理的解釋。

轉換應該在unsigned數組參數之前工作。

Copy(addr, (Int16[])someUnsignedArray, 0, len); 
+0

VB.NET確實具有無符號類型複製支持,你只需要指定類型名稱而不是語言別名,例如'昏暗的foo作爲UInt16'。 – Dai

+0

@dai好吧,我會從我的答案中刪除。 – doug65536

+0

(Int16 [])給出類型轉換錯誤。這是我想要做的:http://stackoverflow.com/questions/28595903/copy-from-intptr-16-bit-array-to-managed-ushort –

0

認爲Marshal沒有因爲CLS遵從性的Copy(IntPtr, UInt16[], Int32, Int32)過載(CLS遵從的原則是無符號整數運算不暴露給消費者,我不同意這個規則FWIW)。

隨着編組,所有重要的是元素的大小。簽名只是次要的問題。我會使用ByteInt16重載,然後做我自己的投射,否則我會使用不安全的指針。

IntPtr unmanagedArray = ... 

Int16[] destination0 = new Int16[ count ]; 
Marshal.Copy(unmanagedArray, destination0, 0, count); 

UInt16[] destinion1 = destination0.OfType<UInt16>().ToArray(); // Linq extension method 
+0

這將刪除所有數據,因爲它全部是和不是看到我的問題:http://stackoverflow.com/questions/28595903/copy-from-intptr-16-bit-array-to-managed-ushort –

1

使用不安全的代碼:

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); 

可以容易地適應於UINT []和ULONG [](調整每個元件的字節數)

相關問題