gpt4 book ai didi

c# - Marshal - 我需要释放任何资源吗?

转载 作者:太空狗 更新时间:2023-10-29 21:27:54 25 4
gpt4 key购买 nike

我正在使用以下方法将 byte[] 转换为 Bitmap:

    public static Bitmap ByteArrayToBitmap(byte[] byteArray)
{
int width = 2144;
int height = 3;
Bitmap bitmapImage = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
BitmapData bmpData = bitmapImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
IntPtr ptr = bmpData.Scan0;

try
{
Marshal.Copy(byteArray, 0, ptr, byteArray.Length);
bitmapImage.UnlockBits(bmpData);
return bitmapImage;
}
finally
{
//Marshal.FreeHGlobal(ptr); //Do I need this?
}
}

只是想知道我是否需要在这里释放任何资源?尝试调用 Marshal.FreeHGlobal(ptr),但出现此错误:

Invalid access to memory location.

谁能指导一下?

此外,仅供引用,我可以使用 MemoryStreambyte[] 中获取 Bitmap,但我得到的是“参数无效”在这种情况下异常(exception)。这就是为什么选择前往 Marshal 的原因。

最佳答案

只有在使用 AllocHGlobal 时才使用 FreeHGlobal。你没有,所以不要调用它。您确实分配了非托管内存,它是由 new Bitmap 完成的。这是由 Dispose() 或 GC 释放的。之后。

您当然应该使用 finally block ,这是您调用 UnlockBits() 的地方。即“释放”指针。

关于c# - Marshal - 我需要释放任何资源吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com