C# 封送。复制失败

C# 封送。复制失败,c#,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; nam

我的问题是,
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;
        }
    }
}

您在此行中放错了括号:

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

int size = Marshal.SizeOf(fileData[0])*fileData.Length;
当然,由于数据类型是
byte
,因此您可以使用

int size = fileData.Length;

为什么要将其标记为[c++-cli]?这看起来像C#。我认为封送副本是C++/cli的一部分。通过这种方式,您可以将托管字节[]复制到uint8*。。。但也许我错了。Copy是.NET运行时库的一部分。您的代码与C++/CLI的连接与与VB.NET或F#的连接相同。稍后我将使用此代码将IntPtr连接到C++/CLI项目中。但我会重新标记这个问题