包含字节数组的编组结构

时间:2014-10-03 08:14:02

标签: marshalling

我第二天一直在努力学习如何传递一个结构,包含byte到c ++ dll的数组。也就是说,我不知道如何编组C#结构。这是我的代码:

in C++ dll:

    struct Image
    {
        int Width;
        int Height;
        int Depth;
        uchar *Data;
    };
    .....
__declspec(dllexport) void DirectTransform(Image *InImage, Image*DestImage)  
{
...Implementation...
}

在C#程序中:

    [StructLayout(LayoutKind.Sequential)]
     struct ImageData
    {
        public int Width;
        public int Height;
        public int Depth;
        [MarshalAs(UnmanagedType.LPArray)]
        public byte[] Data;
    }
 [DllImport("MyDll.dll",CallingConvention=CallingConvention.Cdecl)]
        public static extern void DirectTransform(ImageData Src, ImageData Dest);

//Fill out both structures..

        DirectTransform(Image, DestImage);

在调用DirectTransform时抛出异常,并说:

  

无法整理字段'数据'类型' ImageData':无效的托管/非托管   类型组合(数组字段必须与ByValArray或   的SafeArray)。

当我将LPArray更改为ByValArray并指向数组的大小(在本例中为202500)时,它也不起作用,因为它的大小太大。使用SafeArray时,程序在DLL中失败并显示消息:

  

尝试读取或写入受保护的内存。这通常是一个   指示其他内存已损坏。   结构中的数据是错误的。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

看看这个question

您可以尝试将指针传递给数组,例如整数长度字段。 这样做,您需要使用Marshal.AllocHGlobal手动分配非托管内存,调用您的函数,然后在finally块中调用 - 使用Marshal.FreeHGlobal后自行清除

使用Marshal.Copy方法将数据复制到已分配的内存中。

相关问题