PtrToStructure()生成SafeArrayTypeMismatchException [英] PtrToStructure() generates SafeArrayTypeMismatchException

查看:84
本文介绍了PtrToStructure()生成SafeArrayTypeMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,

请帮助我找出我不断得到的SafeArrayTypeMismatchException.我需要将struct传递给非托管DLL. struct成员之一是可变长度数组.非托管代码将使用数据填充它,然后我的C#代码将使用数据.

方法:
1.使用StructureToPtr()为我的结构获取IntPtr,当然也要进行内存分配.
2.调用非托管函数,并将IntPtr作为参数传递
3.使用PtrToStructure()
获取填充的结构

如果出于练习目的,我将StructureToPtr()PtrToStructure()背对背调用,则没有例外.

如果我在StructureToPtr()PtrToStructure()之间对非托管DLL进行调用,则PtrToStructure()会生成SafeArrayTypeMismatchException. SafeArrayTypeMismatchException的描述是数组的运行时类型与元数据中记录的子类型之间发生不匹配."

任何建议,见解或参考都非常感谢!

如果需要,我可以发布我的代码.

-Nick

Folks,

Please help me chase out a SafeArrayTypeMismatchException that I keep getting. I need to pass a struct to unmanaged DLL. One of the struct members is a variable-length array. Unmanaged code will populate it with data, then my C# code will use the data.

Approach:
1. Get IntPtr for my structure using StructureToPtr(), do the memory allocation too, of course.
2. Call unmanaged function, and pass IntPtr as a parameter
3. Get the populated structure using PtrToStructure()


If for the purposes of an exercise I call StructureToPtr() and PtrToStructure() back-to-back there are no exceptions.

PtrToStructure() generates SafeArrayTypeMismatchException, if I put a call to unmanaged DLL between StructureToPtr() and PtrToStructure(). The description for SafeArrayTypeMismatchException is "Mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata."

Any suggestion, insight or reference is really appreciated!

I can post my code if needed.

- Nick

推荐答案

您是否已使用System.Runtime.InteropServices命名空间中的适当属性确保您的结构适合于互操作?
这是一个示例:
Have you made sure that your struct is suitable for interop using appropriate attributes from the System.Runtime.InteropServices namespace?

Here is one example:
[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Unicode )]
    public struct OSVERSIONINFO
    {
        internal int dwOSVersionInfoSize;
        /// <summary>
        /// Major
        /// </summary>
        public int dwMajorVersion;
        /// <summary>
        /// Minor
        /// </summary>
        public int dwMinorVersion;
        /// <summary>
        /// Build
        /// </summary>
        public int dwBuildNumber;
        /// <summary>
        /// Platform type
        /// </summary>
        public PlatformType dwPlatformId;
        /// <summary>
        /// Null-terminated string that provides arbitrary 
        /// additional information about the OS.
        /// </summary>
        [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 256 )]
        public string szCSDVersion;
    }



问候
Espen Harlinn



regards
Espen Harlinn


这篇关于PtrToStructure()生成SafeArrayTypeMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆