views:

267

answers:

1

I also used VT_RECORD. But didn't got success in passing safearray of UDTs.

        [ComVisible(true)]
        [StructLayout(LayoutKind.Sequential)]
        public class MY_CLASS
        {
            [MarshalAs(UnmanagedType.U4)]
            public Int32 width;
            [MarshalAs(UnmanagedType.U4)]
            public Int32 height;
        };

    [DllImport("mydll.dll")]
    public static extern Int32 GetTypes(
        [In, Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(MY_CLASS))]MY_CLASS[] myClass,
        [In, Out][MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(Guid))]Guid[] guids
        );

If i communicate with my unmanaged code without 1st parameter, Then there is no error in passing "guids" parameter to unmanaged code.

I also able to cast elements of obtained SAFEARRAY at unmanaged side to GUID type. But If i tried to pass my UDT class MY_CLASS to unmanaged code with SAFEARRAY then it fails on managed code. (as above code snippet)

It shows exception "An unhandled exception of type 'System.Runtime.InteropServices.SafeArrayTypeMismatchException' occurred in myapp.exe" "Additional information: Specified array was not of the expected type."

Plz help me in such a situation to pass SAFEARRAY of UDTs to unmaged code.

A: 

I got one solution to this problem.


I tried an alternative to this problem. I passed UDT having SAFEARRAYs as its members to unmanaged code.

Here is managed code that I followed,

    [ComVisible(true)]
    [StructLayout(LayoutKind.Sequential)]
    public class MY_CLASS
    {
        [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.I4)]
        public Int32[] width;
        [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.I4)]
        public Int32[] height;
    };

    [DllImport("mydll.dll")]
    public static extern Int32 GetTypes(
        [In, Out] MY_CLASS myClass
        );

and on unmanaged side,

    typedef struct _MY_STRUCT
    {
        SAFEARRAY * pWidths;
        SAFEARRAY * pHeights;
    }MY_STRUCT;

    HRESULT GetTypes(MY_STRUCT * pMyStruct)
    {
        // Here I can use pMyStruct->pWidths or pMyStruct->pHeights
        //      paramater as safearray of int32 type.
        // I can modify it's element and it will be visible
        //      on managed side.

        return S_OK;
    }

I uses this type of mechanism to pass UDT having array of Value-Types instead of passing array of UDTs.

themilan