开发者

How to pass SAFEARRAY of UDTs to unmaged code from C#

开发者 https://www.devze.com 2022-12-27 13:16 出处:网络
I also used VT_RECORD. But didn\'t got success in passing safearray of UDTs. [ComVisible(true)] [StructLayout(LayoutKind.Sequential)]

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 st开发者_如何学JAVAatic 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号