.NET Marshal.Copy的一个应用(A sample of Marshal.Copy)
Marshal.Copy在对有C++代码和C#代码混合的项目中很有用,它能在非托管指针和托管数组间起到相互转换作用。
Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)
Copies data from a managed array to an unmanaged memory pointer, or from an unmanaged memory pointer to a managed array.
把数据从一个托管的数组拷贝到一个非托管的内存指针, 或从一个非托管的内存指针拷贝到一个托管的数组。
Marchal.Copy有很多形态,其四个参数有很多类型变化:
Copy(array<Byte>[]()[], Int32, IntPtr, Int32)
Copy(array<Char>[]()[], Int32, IntPtr, Int32)
Copy(array<Double>[]()[], Int32, IntPtr, Int32)
Copy(array<Int16>[]()[], Int32, IntPtr, Int32)
Copy(array<Int32>[]()[], Int32, IntPtr, Int32)
Copy(array<Int64>[]()[], Int32, IntPtr, Int32)
Copy(IntPtr, array<Byte>[]()[], Int32, Int32)
Copy(IntPtr, array<Char>[]()[], Int32, Int32)
Copy(IntPtr, array<Double>[]()[], Int32, Int32)
Copy(IntPtr, array<Int16>[]()[], Int32, Int32)
Copy(IntPtr, array<Int32>[]()[], Int32, Int32)
Copy(IntPtr, array<Int64>[]()[], Int32, Int32)
Copy(IntPtr, array<IntPtr>[]()[], Int32, Int32)
Copy(IntPtr, array<Single>[]()[], Int32, Int32)
Copy(array<IntPtr>[]()[], Int32, IntPtr, Int32)
Copy(array<Single>[]()[], Int32, IntPtr, Int32)
一个项目中有一个USB应用,代码是C++,用到了指针,而到C#代码中,需要将指针内存的数据拷贝到数组中,我用的简单代码如下:
源 (source): byte* ReceiveData
目的(target): byte[] arrRecData
长度(length): ReceiveLength
//The following 2 lines code just for debug — copy point to array
byte[] arrRecData = new byte[(int)ReceiveLength];
Marshal.Copy((IntPtr)ReceiveData, arrRecData, 0, (int)ReceiveLength);
这样可以在C#中安全使用arrRecData数组了。

Leave a Reply