首页 > 解决方案 > Marshal.Copy 导致暗恋

问题描述

我想在一个线程中翻转一张“tiff”的图片,但使用“Marshal.Copy”时可能会导致粉碎

我的代码:

public static bool ImageMirrorCv(ref int[] image, int width, int height, int mirrorNum)
    {
        try
        {
            //以X轴,垂直翻转
            if (mirrorNum == 0)
            {
                Mat mt = new Mat(height, width, MatType.CV_32F);
                if ((mt.Height * mt.Width) != image.Length)
                    return false;
                Marshal.Copy(image, 0, mt.Data, image.Count());
                Cv2.Flip(mt, mt, FlipMode.X);
                if ((mt.Height * mt.Width) != image.Length)
                    return false;
                Marshal.Copy(mt.Data, image, 0, image.Count());
            }
            //以Y轴,水平翻转
            else if (mirrorNum == 1)
            {
                Mat mt = new Mat(height, width, MatType.CV_32F);
                if ((mt.Height * mt.Width) != image.Length)
                    return false;
                Marshal.Copy(image, 0, mt.Data, image.Count());
                Cv2.Flip(mt, mt, FlipMode.Y);
                if ((mt.Height * mt.Width) != image.Length)
                    return false;
                Marshal.Copy(mt.Data, image, 0, image.Count());
            }
            //XY翻转
            else if (mirrorNum == -1)
            {
                Mat mt = new Mat(height, width, MatType.CV_32F);
                if ((mt.Height * mt.Width) != image.Length)
                    return false;
                Marshal.Copy(image, 0, mt.Data, image.Count());
                Cv2.Flip(mt, mt, FlipMode.XY);
                if ((mt.Height * mt.Width) != image.Length)
                    return false;
                Marshal.Copy(mt.Data, image, 0, image.Count());
            }
            else
            {

            }
            return true;
        }
        catch(Exception ex)
        {
            Utility.LogControl.Error(ex.ToString());
            return false;
        }
        
    }

params:image是一个arrary int[2048*2048],高宽是2048,mirrorNum是flip的类型。通常是1,出现概率大约0.01%

事件查看器显示:

System.AccessViolationException at System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr, System.Object, Int32, Int32) 在 Utility.Function.ImageMirrorCv(Int32[] ByRef, Int32, Int32, Int32) 在 DataInterface.ImageProcess.Mirror(System .Object) 在 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) 在 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback , System.Object, Boolean) 在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 在 System.Threading.ThreadPoolWorkQueue.Dispatch()

标签: marshalling

解决方案


推荐阅读