Marshaling C ++锯齿状数组给出了#34;无效的托管/非托管类型组合"错误

时间:2018-05-22 05:35:37

标签: c++ interop

这是我的C ++定义:

typedef struct _DRIVER_VERSION
{
DWORD DriverNum;
CHAR Version[16][16];
} DRIVER_INFO, *PDRIVER_INFO;

这是我的C#互操作代码:

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Version16
{
    [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)]
    public string VerInfo;
}


/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DRIVER_VERSION
{
    public System.UInt32 DriverNum;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
    public Version16 Version16;

}

    public static class InstallDeviceClass
{
    [DllImport(@"driver.dll")]
    public static extern SResultEnum s4drv_GetDriverInfo(ref _DRIVER_VERSION pDrvInfo);
}

    static void Main(string[] args)
    {
        _DRIVER_VERSION version=new _DRIVER_VERSION();
        var s4Res = InstallDeviceClass.s4drv_GetDriverInfo(ref version);
    }

然而,当我运行代码时,我会得到

  

$例外{&#34;无法编组字段&#39;版本16&#39;类型   &#39; _DRIVER_VERSION&#39;:无效的托管/非托管类型组合(此   值类型必须与Struct)配对。&#34;:&#34;&#34;} System.TypeLoadException

出现这种情况的原因是什么,以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

修复

/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct _DRIVER_VERSION
{
    public System.UInt32 DriverNum;
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
    public Version16[] Version16;

}

Version16应该是数组,而不是字段