Click here to Skip to main content
15,898,732 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Posted
Comments
Sergey Alexandrovich Kryukov 27-Dec-10 20:44pm    
Needs code sample on .NET (C#) side as well as on native side; at least definition of types and method profile

1 solution

Have you made sure that your struct is suitable for interop using appropriate attributes from the System.Runtime.InteropServices namespace?

Here is one example:
XML
[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;
    }


regards
Espen Harlinn
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900