C# IntPtr转byte数组、byte[]转Intptr、IntPtr转换为raw数据、Marshal.Copy方法

  • Post author:
  • Post category:其他



C# IntPtr转byte数组、byte[]转Intptr、IntPtr转换为raw数据、Marshal.Copy方法

//IntPtr转换为raw数据
IntPtr Destination = IntPtr.Zero;
int tempSize = (int)(width * height * 2);
//申请存空间
Destination = Marshal.AllocHGlobal(tempSize);

int tempSize = (int)(width * height * 2);
byte[] managedArray = new byte[tempSize];
//Marshal.Copy方法是用来在托管对象(数组)和非托管对象(IntPtr)之间进行内容的复制
Marshal.Copy(Destination, managedArray, 0, tempSize);
File.WriteAllBytes($"image.raw", managedArray);

//释放内存空间
Marshal.FreeHGlobal(Destination);


//byte[]转IntPtr
//输入buye[],返回IntPtr ,不使用Marshal创建新的堆,节省内存开销,也避免忘记释放导致的问题
IntPtr ArrToPtr(byte[] array)
{
    return System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(array, 0);
}

//IntPtr转Stream
void PtrToStream(IntPtr pRet)
{
	 byte* memBytePtr = (byte*)pRet.ToPointer();
     UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, Length, Length, FileAccess.Read);
}



版权声明:本文为wangnaisheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。