Marshal.Copy失败了

时间:2015-04-18 21:15:14

标签: c#

我的问题是Marshal.Copy因大小而失败。 我的大小由于某种原因是4,虽然我的阵列的实际大小超过200kb。 你能用大小来解释我的错误吗?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    public class ImageData
    {
        public IntPtr Data { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public int ColorOrder { get; set; }

        public void ReadHeaderLessImage(string path, int width, int height,int colorOrder)
        {
            byte[] fileData = null;
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }
            fileData = File.ReadAllBytes(path);
            this.Height = height;
            this.Width = width;
            this.ColorOrder = colorOrder;
            int size = Marshal.SizeOf(fileData[0]*fileData.Length);
            this.Data = Marshal.AllocHGlobal(size);

            try
            {
                Marshal.Copy(fileData, 0, this.Data, size);
            }
            catch (Exception ex)
            {
                throw;
            }
            return;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你在这一行中错开了一个括号:

int size = Marshal.SizeOf(fileData[0]*fileData.Length);

应该是

int size = Marshal.SizeOf(fileData[0])*fileData.Length;

当然,由于数据类型为byte,您只需使用

即可
int size = fileData.Length;