Exemplo n.º 1
1
 internal ComMethodInformation(bool hasvarargs, bool hasoptional, ParameterInformation[] arguments, Type returnType, int dispId, COM.INVOKEKIND invokekind)
     : base(hasvarargs, hasoptional, arguments)
 {
     this.ReturnType = returnType;
     this.DispId = dispId;
     this.InvokeKind = invokekind;
 }
Exemplo n.º 2
0
        // This method is intended for use through reflection and should not be used directly
        public static unsafe int IDispatchInvoke(
            IntPtr dispatchPointer,
            int memberDispId,
            ComTypes.INVOKEKIND flags,
            ref ComTypes.DISPPARAMS dispParams,
            out Variant result,
            out ExcepInfo excepInfo,
            out uint argErr)
        {
            Guid IID_NULL = default;

            fixed(ComTypes.DISPPARAMS *pDispParams = &dispParams)
            fixed(Variant * pResult      = &result)
            fixed(ExcepInfo * pExcepInfo = &excepInfo)
            fixed(uint *pArgErr          = &argErr)
            {
                var pfnIDispatchInvoke = (delegate * stdcall <IntPtr, int, Guid *, int, ushort, ComTypes.DISPPARAMS *, Variant *, ExcepInfo *, uint *, int>)
                                             (*(*(void ***)dispatchPointer + 6 /* IDispatch.Invoke slot */));

                int hresult = pfnIDispatchInvoke(dispatchPointer,
                                                 memberDispId, &IID_NULL, 0, (ushort)flags, pDispParams, pResult, pExcepInfo, pArgErr);

                if (hresult == ComHresults.DISP_E_MEMBERNOTFOUND &&
                    (flags & ComTypes.INVOKEKIND.INVOKE_FUNC) != 0 &&
                    (flags & (ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT | ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF)) == 0)
                {
                    // Re-invoke with no result argument to accomodate Word
                    hresult = pfnIDispatchInvoke(dispatchPointer,
                                                 memberDispId, &IID_NULL, 0, (ushort)ComTypes.INVOKEKIND.INVOKE_FUNC, pDispParams, null, pExcepInfo, pArgErr);
                }

                return(hresult);
            }
        }
Exemplo n.º 3
0
        public void GetElementNames(System.Runtime.InteropServices.ComTypes.INVOKEKIND kind, Action <String, Int32> add)
        {
            try {
                for (int i = 0; i < this.TypeAttr.cFuncs; i++)
                {
                    IntPtr pFuncDesc = IntPtr.Zero;
                    System.Runtime.InteropServices.ComTypes.FUNCDESC funcDesc;
                    string strName, strDocString, strHelpFile;
                    int    dwHelpContext;

                    _typeInfo.GetFuncDesc(i, out pFuncDesc);
                    funcDesc = (System.Runtime.InteropServices.ComTypes.FUNCDESC)
                               Marshal.PtrToStructure(pFuncDesc, typeof(System.Runtime.InteropServices.ComTypes.FUNCDESC));

                    if (funcDesc.invkind == kind)
                    {
                        _typeInfo.GetDocumentation(funcDesc.memid, out strName, out strDocString, out dwHelpContext, out strHelpFile);
                        add(strName, funcDesc.cParams);
                    }
                }
            }
            catch (System.Exception ex) {
                throw ex;
            }
        }
Exemplo n.º 4
0
        // This method is intended for use through reflection and should not be used directly
        public static int IDispatchInvoke(
            IntPtr dispatchPointer,
            int memberDispId,
            ComTypes.INVOKEKIND flags,
            ref ComTypes.DISPPARAMS dispParams,
            out Variant result,
            out ExcepInfo excepInfo,
            out uint argErr)
        {
            int hresult = s_iDispatchInvoke(
                dispatchPointer,
                memberDispId,
                flags,
                ref dispParams,
                out result,
                out excepInfo,
                out argErr
                );

            if (hresult == ComHresults.DISP_E_MEMBERNOTFOUND &&
                (flags & ComTypes.INVOKEKIND.INVOKE_FUNC) != 0 &&
                (flags & (ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT | ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF)) == 0)
            {
                // Re-invoke with no result argument to accomodate Word
                hresult = _IDispatchInvokeNoResult(
                    dispatchPointer,
                    memberDispId,
                    ComTypes.INVOKEKIND.INVOKE_FUNC,
                    ref dispParams,
                    out result,
                    out excepInfo,
                    out argErr);
            }
            return(hresult);
        }
Exemplo n.º 5
0
 internal ComMethodInformation(bool hasvarargs, bool hasoptional, ParameterInformation[] arguments, Type returnType, int dispId, COM.INVOKEKIND invokekind)
     : base(hasvarargs, hasoptional, arguments)
 {
     this.ReturnType = returnType;
     this.DispId     = dispId;
     this.InvokeKind = invokekind;
 }
Exemplo n.º 6
0
 void Invoke(
     int dispIdMember,
     ref Guid riid,
     int lcid,
     ComTypes.INVOKEKIND wFlags,
     ref ComTypes.DISPPARAMS pDispParams,
     IntPtr VarResult,
     IntPtr pExcepInfo,
     IntPtr puArgErr);
Exemplo n.º 7
0
        void ComTypes.ITypeInfo.GetDllEntry(int memid, ComTypes.INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal)
        {
            // for some reason, the ComTypes.ITypeInfo definition for GetDllEntry uses the raw pointers for strings here,
            // just like our unfriendly version.  This makes it much easier for us to forward on
            var hr = _this_Internal.GetDllEntry(memid, invKind, pBstrDllName, pBstrName, pwOrdinal);

            if (ComHelper.HRESULT_FAILED(hr))
            {
                HandleBadHRESULT(hr);
            }
        }
Exemplo n.º 8
0
 public static int InvokeInternal(
     IntPtr thisPtr,
     int dispIdMember,
     IntPtr riid,
     int lcid,
     ComTypes.INVOKEKIND wFlags,
     IntPtr pDispParams,
     IntPtr VarResult,
     IntPtr pExcepInfo,
     IntPtr puArgErr)
 {
     return(0); // S_OK;
 }
Exemplo n.º 9
0
        void ComTypes.ITypeInfo.AddressOfMember(int memid, ComTypes.INVOKEKIND invKind, out IntPtr ppv)
        {
            // initialize out parameters
            ppv = default;

            using (var outPpv = AddressableVariables.Create <IntPtr>())
            {
                var hr = _this_Internal.AddressOfMember(memid, invKind, outPpv.Address);
                if (ComHelper.HRESULT_FAILED(hr))
                {
                    HandleBadHRESULT(hr);
                }
                ppv = outPpv.Value;
            }
        }
Exemplo n.º 10
0
        public static void GetAllFuncCustData(int memberid, INVOKEKIND invokekind, ITypeInfo ti, ref List <string> lprops)
        {
            if (!(ti is ITypeInfo2 t2))
            {
                return;
            }

            var custdata = new CUSTDATA();
            var ptr      = Marshal.AllocHGlobal(Marshal.SizeOf(custdata));

            try
            {
                t2.GetFuncIndexOfMemId(memberid, invokekind, out var index);
                t2.GetAllFuncCustData(index, ptr);
                try
                {
                    custdata = Marshal.PtrToStructure <CUSTDATA>(ptr);
                    for (var x = 0; x < custdata.cCustData; x++)
                    {
                        var item    = new CUSTDATAITEM(); // just to size it for next line
                        var itemPtr = custdata.prgCustData + (x * Marshal.SizeOf(item));
                        item = Marshal.PtrToStructure <CUSTDATAITEM>(itemPtr);
                        lprops.Add($"custom({item.guid}, {ITypeInfoXtra.QuoteString(item.varValue)})");
                    }
                }
                finally
                {
                    NativeMethods.ClearCustData(ptr);
                }
            }
            catch (COMException e)
            {
                const int TYPE_E_ELEMENTNOTFOUND = unchecked ((int)0x8002802B);
                if (e.HResult != TYPE_E_ELEMENTNOTFOUND)
                {
                    throw;
                }

                // not found; ignore
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }
Exemplo n.º 11
0
 public static int InvokeInternal(
     IntPtr thisPtr,
     int dispIdMember,
     ref Guid riid,
     int lcid,
     ComTypes.INVOKEKIND wFlags,
     ref ComTypes.DISPPARAMS pDispParams,
     IntPtr VarResult,
     IntPtr pExcepInfo,
     IntPtr puArgErr)
 {
     try
     {
         var inst = ComInterfaceDispatch.GetInstance <IDispatch>((ComInterfaceDispatch *)thisPtr);
         inst.Invoke(dispIdMember, ref riid, lcid, wFlags, ref pDispParams, VarResult, pExcepInfo, puArgErr);
     }
     catch (Exception e)
     {
         return(e.HResult);
     }
     return(0); // S_OK;
 }
Exemplo n.º 12
0
        public override int GetDllEntry(int memid, ComTypes.INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal)
        {
            var hr = _target_ITypeInfo.GetDllEntry(memid, invKind, pBstrDllName, pBstrName, pwOrdinal);

            return(ComHelper.HRESULT_FAILED(hr) ? HandleBadHRESULT(hr) : hr);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Invoke the COM member
        /// </summary>
        /// <param name="target">IDispatch object</param>
        /// <param name="dispId">Dispatch identifier that identifies the member</param>
        /// <param name="args">Arguments passed in</param>
        /// <param name="byRef">Boolean array that indicates by-Ref parameters</param>
        /// <param name="invokeKind">Invocation kind</param>
        /// <returns></returns>
        internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind)
        {
            Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in.");
            Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length,
                               "If 'args' and 'byRef' are not null, then they should be one-on-one mapping.");

            int argCount = args != null ? args.Length : 0;
            int refCount = byRef != null?byRef.Count(c => c) : 0;

            IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero;

            try
            {
                // Package arguments
                if (argCount > 0)
                {
                    variantArgArray = NewVariantArray(argCount);

                    int refIndex = 0;
                    for (int i = 0; i < argCount; i++)
                    {
                        // !! The arguments should be in REVERSED order!!
                        int    actualIndex = argCount - i - 1;
                        IntPtr varArgPtr   = variantArgArray + s_variantSize * actualIndex;

                        // If need to pass by ref, create a by-ref variant
                        if (byRef != null && byRef[i])
                        {
                            // Allocate memory for temporary VARIANTs used in by-ref marshalling
                            if (tmpVariants == IntPtr.Zero)
                            {
                                tmpVariants = NewVariantArray(refCount);
                            }

                            // Create a VARIANT that the by-ref VARIANT points to
                            IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex;
                            Marshal.GetNativeVariantForObject(args[i], tmpVarPtr);

                            // Create the by-ref VARIANT
                            MakeByRefVariant(tmpVarPtr, varArgPtr);
                            refIndex++;
                        }
                        else
                        {
                            Marshal.GetNativeVariantForObject(args[i], varArgPtr);
                        }
                    }
                }

                var paramArray = new COM.DISPPARAMS[1];
                paramArray[0].rgvarg = variantArgArray;
                paramArray[0].cArgs  = argCount;

                if (invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUTREF)
                {
                    // For property putters, the first DISPID argument needs to be DISPID_PROPERTYPUT
                    dispIdArray = Marshal.AllocCoTaskMem(4); // Allocate 4 bytes to hold a 32-bit signed integer
                    Marshal.WriteInt32(dispIdArray, DISPID_PROPERTYPUT);

                    paramArray[0].cNamedArgs        = 1;
                    paramArray[0].rgdispidNamedArgs = dispIdArray;
                }
                else
                {
                    // Otherwise, no named parameters are necessary since powershell parser doesn't support named parameter
                    paramArray[0].cNamedArgs        = 0;
                    paramArray[0].rgdispidNamedArgs = IntPtr.Zero;
                }

                // Make the call
                EXCEPINFO info   = default(EXCEPINFO);
                object    result = null;

                try
                {
                    // 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'.
                    // Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it.
                    uint puArgErrNotUsed = 0;
                    target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed);
                }
                catch (Exception innerException)
                {
                    // When 'IDispatch.Invoke' returns error code, CLR will raise exception based on internal HR-to-Exception mapping.
                    // Description of the return code can be found at https://msdn.microsoft.com/library/windows/desktop/ms221479(v=vs.85).aspx
                    // According to CoreCLR team (yzha), the exception needs to be wrapped as an inner exception of TargetInvocationException.

                    string exceptionMsg = null;
                    if (innerException.HResult == DISP_E_EXCEPTION)
                    {
                        // Invoke was successful but the actual underlying method failed.
                        // In this case, we use EXCEPINFO to get additional error info.

                        // Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception.
                        int code = info.scode != 0 ? info.scode : info.wCode;
                        innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException;

                        // Get the richer error description if it's available.
                        if (info.bstrDescription != IntPtr.Zero)
                        {
                            exceptionMsg = Marshal.PtrToStringBSTR(info.bstrDescription);
                            Marshal.FreeBSTR(info.bstrDescription);
                        }

                        // Free the BSTRs
                        if (info.bstrSource != IntPtr.Zero)
                        {
                            Marshal.FreeBSTR(info.bstrSource);
                        }
                        if (info.bstrHelpFile != IntPtr.Zero)
                        {
                            Marshal.FreeBSTR(info.bstrHelpFile);
                        }
                    }

                    var outerException = exceptionMsg == null
                                              ? new TargetInvocationException(innerException)
                                              : new TargetInvocationException(exceptionMsg, innerException);
                    throw outerException;
                }

                // Now back propagate the by-ref arguments
                if (refCount > 0)
                {
                    for (int i = 0; i < argCount; i++)
                    {
                        // !! The arguments should be in REVERSED order!!
                        int actualIndex = argCount - i - 1;

                        // If need to pass by ref, back propagate
                        if (byRef != null && byRef[i])
                        {
                            args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex);
                        }
                    }
                }

                return(result);
            }
            finally
            {
                // Free the variant argument array
                if (variantArgArray != IntPtr.Zero)
                {
                    for (int i = 0; i < argCount; i++)
                    {
                        VariantClear(variantArgArray + s_variantSize * i);
                    }
                    Marshal.FreeCoTaskMem(variantArgArray);
                }

                // Free the dispId array
                if (dispIdArray != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dispIdArray);
                }

                // Free the temporary variants created when handling by-Ref arguments
                if (tmpVariants != IntPtr.Zero)
                {
                    for (int i = 0; i < refCount; i++)
                    {
                        VariantClear(tmpVariants + s_variantSize * i);
                    }
                    Marshal.FreeCoTaskMem(tmpVariants);
                }
            }
        }
Exemplo n.º 14
0
 public abstract int GetDllEntry(int memid, ComTypes.INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal);
Exemplo n.º 15
0
 public abstract int AddressOfMember(int memid, ComTypes.INVOKEKIND invKind, IntPtr ppv);
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            object Res = 1;

            int a     = 0;
            Car myCar = new Car();
            //Type type = typeof(Car);
            ICreateCar iCrCar = (ICreateCar)myCar;
            IStats     iStCar = (IStats)myCar;

            //Console.WriteLine("Напишите имя: ");
            //iCrCar.SetPetName(Console.ReadLine());
            //IStats iStCar = (IStats)myCar;
            //string st = "";
            //iStCar.GetPetName(ref st);
            //Console.WriteLine(st);
            iCrCar.SetPetName("Lolipop");
            iCrCar.SetMaxSpeed(67);
            IDispatch disp = (IDispatch)myCar;

            iStCar.DisplayStats();
            disp.GetTypeInfoCount(out a);

            Console.WriteLine(a.ToString());

            int[] t    = new int[1];
            Guid  guid = new Guid();

            disp.GetIDsOfNames(ref guid, new string[] { "GetMaxSpeed" }, 1, 1, t);
            Console.WriteLine("Max speed " + t[0].ToString());

            var arg      = 51;
            var pVariant = Marshal.AllocCoTaskMem(16);

            Marshal.GetNativeVariantForObject(arg, pVariant);
            System.Runtime.InteropServices.ComTypes.DISPPARAMS par = new System.Runtime.InteropServices.ComTypes.DISPPARAMS()
            {
                cArgs             = 1,
                cNamedArgs        = 0,
                rgdispidNamedArgs = IntPtr.Zero,
                rgvarg            = pVariant
            };
            System.Runtime.InteropServices.ComTypes.INVOKEKIND flags = new System.Runtime.InteropServices.ComTypes.INVOKEKIND();
            IntPtr info     = new IntPtr();
            IntPtr puArgErr = new IntPtr();

            disp.Invoke(4, guid, 1, flags, par, out Res, info, puArgErr);
            disp.Invoke(1, guid, 1, flags, par, out Res, info, puArgErr);
            Console.WriteLine("Res = " + Res.ToString());

            var arg_6 = "";

            Marshal.GetNativeVariantForObject(arg_6, pVariant);
            System.Runtime.InteropServices.ComTypes.DISPPARAMS par_6 = new System.Runtime.InteropServices.ComTypes.DISPPARAMS()
            {
                cArgs             = 1,
                cNamedArgs        = 0,
                rgdispidNamedArgs = IntPtr.Zero,
                rgvarg            = pVariant
            };
            System.Runtime.InteropServices.ComTypes.INVOKEKIND flags_6 = new System.Runtime.InteropServices.ComTypes.INVOKEKIND();
            disp.Invoke(6, guid, 1, flags_6, par_6, out Res, info, puArgErr);


            Console.WriteLine("Res = " + Res.ToString());
            Console.ReadKey();
        }
        unsafe void NativeMethods.IDispatch.Invoke(int dispid, ref Guid riid, int lcid, System.Runtime.InteropServices.ComTypes.INVOKEKIND wFlags, ref System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, IntPtr pvarResult, IntPtr pExcepInfo, IntPtr puArgErr)
        {
            ComEventsMethod method = this.FindMethod(dispid);

            if (method != null)
            {
                int      num2;
                object[] args      = new object[pDispParams.cArgs];
                int[]    numArray  = new int[pDispParams.cArgs];
                bool[]   flagArray = new bool[pDispParams.cArgs];
                System.Runtime.InteropServices.Variant *rgvarg = (System.Runtime.InteropServices.Variant *)pDispParams.rgvarg;
                int *rgdispidNamedArgs = (int *)pDispParams.rgdispidNamedArgs;
                int  index             = 0;
                while (index < pDispParams.cNamedArgs)
                {
                    num2            = rgdispidNamedArgs[index];
                    args[num2]      = (rgvarg + index).ToObject();
                    flagArray[num2] = true;
                    if ((rgvarg + index).IsByRef)
                    {
                        numArray[num2] = index;
                    }
                    else
                    {
                        numArray[num2] = -1;
                    }
                    index++;
                }
                num2 = 0;
                while (index < pDispParams.cArgs)
                {
                    while (flagArray[num2])
                    {
                        num2++;
                    }
                    System.Runtime.InteropServices.Variant *variantPtr2 = rgvarg + ((pDispParams.cArgs - 1) - index);
                    args[num2] = variantPtr2.ToObject();
                    if (variantPtr2.IsByRef)
                    {
                        numArray[num2] = (pDispParams.cArgs - 1) - index;
                    }
                    else
                    {
                        numArray[num2] = -1;
                    }
                    num2++;
                    index++;
                }
                object obj2 = method.Invoke(args);
                if (pvarResult != IntPtr.Zero)
                {
                    Marshal.GetNativeVariantForObject(obj2, pvarResult);
                }
                for (index = 0; index < pDispParams.cArgs; index++)
                {
                    int num3 = numArray[index];
                    if (num3 != -1)
                    {
                        (rgvarg + num3).CopyFromIndirect(args[index]);
                    }
                }
            }
        }
Exemplo n.º 18
0
        private static object DynamicInvoke(IDispatch dispatch, int dispID, object[] parameters, ComTypes.INVOKEKIND invokeKind)
        {
            Array.Reverse(parameters);
            IntPtr paramsPtr = Marshal.AllocCoTaskMem(parameters.Length * SizeOfVariant);

            ComTypes.DISPPARAMS[] dispParams = new ComTypes.DISPPARAMS[1];
            if (IsSet(invokeKind))
            {
                dispParams[0].cNamedArgs        = 1;
                dispParams[0].rgdispidNamedArgs = Marshal.AllocCoTaskMem(SizeOfVariant);
                Marshal.Copy(new int[] { DISPID_PROPERTYPUT }, 0, dispParams[0].rgdispidNamedArgs, 1);
            }
            else
            {
                dispParams[0].cNamedArgs        = 0;
                dispParams[0].rgdispidNamedArgs = IntPtr.Zero;
            }
            dispParams[0].cArgs  = parameters.Length;
            dispParams[0].rgvarg = paramsPtr;
            try
            {
                int ptr = paramsPtr.ToInt32();
                foreach (object parameter in parameters)
                {
                    Marshal.GetNativeVariantForObject(parameter, new IntPtr(ptr));
                    ptr += SizeOfVariant;
                }
                Guid     guid   = Guid.Empty;
                object[] result = new object[] { null };
                Marshal.ThrowExceptionForHR(dispatch.Invoke(
                                                dispID,
                                                ref guid,
                                                CultureInfo.CurrentCulture.LCID,
                                                (short)invokeKind,
                                                dispParams,
                                                result,
                                                null,
                                                null));
                return(result[0]);
            }
            finally
            {
                if (dispParams[0].rgdispidNamedArgs != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dispParams[0].rgdispidNamedArgs);
                    dispParams[0].rgdispidNamedArgs = IntPtr.Zero;
                }
                if (dispParams[0].rgvarg != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dispParams[0].rgvarg);
                    dispParams[0].rgvarg = IntPtr.Zero;
                }
                paramsPtr = IntPtr.Zero;
            }
        }
Exemplo n.º 19
0
        private static object DynamicInvoke(IDispatch dispatch, string funcName, object[] parameters, ComTypes.INVOKEKIND invokeKind)
        {
            int dispID = GetDISPID(dispatch, funcName);

            return(DynamicInvoke(dispatch, dispID, parameters, invokeKind));
        }
Exemplo n.º 20
0
        public override int AddressOfMember(int memid, ComTypes.INVOKEKIND invKind, IntPtr ppv)
        {
            var hr = _target_ITypeInfo.AddressOfMember(memid, invKind, ppv);

            return(ComHelper.HRESULT_FAILED(hr) ? HandleBadHRESULT(hr) : hr);
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            // Получаем интерфейс IDispatch
            IDispatch disp = (IDispatch)(new Printer());

            // Получаем число интерфейсов информации типа
            int a = 0;

            disp.GetTypeInfoCount(out a);

            // Массив названий методов
            var namesMaethos = new string[] { "SpeedUp", "QualityUp", "GetMaxSpeed", "GetCurSpeed", "GetCurQuality",
                                              "SetPetName", "SetMaxSpeed", "GetPetName", "DisplayStats" };

            // Массив id методов
            int[] IDs = new int[namesMaethos.Length];

            // Пустой гуид
            Guid guid = new Guid();

            // Получаем массив соответсвующих ID
            disp.GetIDsOfNames(ref guid, namesMaethos, namesMaethos.Length, 1, IDs);

            // Коллекция: ключ - имя метода, значение - ID
            int i           = 0;
            var methodsDict = namesMaethos.ToDictionary(k => k, v => IDs[i++]);

            // Выведем полученные ID
            Console.WriteLine(string.Format("{0, -15} | {1}", "Method name", "ID"));
            foreach (var elem in methodsDict)
            {
                Console.WriteLine(string.Format("{0, -15} | {1}", elem.Key, elem.Value));
            }
            Console.WriteLine("--------------------------");

            // Для получения результата из Get функций
            object result;

            // Последние 2 параметра для Invoke
            var pExcepInfo = new IntPtr();
            var puArgErr   = new IntPtr();

            // 4-й параметр для Invoke
            INVOKEKIND wFlags = new INVOKEKIND();

            // Переменная для передачи аргументов в Set функции
            var pVariant = Marshal.AllocCoTaskMem(10);

            // Преобразуем строку в VARIANT
            Marshal.GetNativeVariantForObject("HP", pVariant);

            // Структура параметров
            DISPPARAMS param = new DISPPARAMS()
            {
                cArgs             = 1,
                cNamedArgs        = 0,
                rgdispidNamedArgs = IntPtr.Zero,
                rgvarg            = pVariant
            };

            // Привсваиваем имя
            disp.Invoke(methodsDict["SetPetName"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);

            Marshal.GetNativeVariantForObject(10, pVariant);
            param.rgvarg = pVariant;

            // Привсваиваем максимальную скорость
            disp.Invoke(methodsDict["SetMaxSpeed"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);

            // Получаем текущую скорость
            disp.Invoke(methodsDict["GetCurSpeed"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);
            Console.WriteLine("Current speed: " + result.ToString());
            int curSpeed = Convert.ToInt32(result);

            // Получаем текущее качество
            disp.Invoke(methodsDict["GetCurQuality"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);
            Console.WriteLine("Current quality: " + result.ToString());

            // Получаем максимальную скорость
            disp.Invoke(methodsDict["GetMaxSpeed"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);
            int maxSpeed = Convert.ToInt32(result);

            Console.WriteLine("-------------------------");

            for (; curSpeed < maxSpeed; curSpeed++)
            {
                disp.Invoke(methodsDict["SpeedUp"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);
                Console.WriteLine("SpeedUp! (+1)");
            }

            Console.WriteLine("-------------------------");

            // Получаем текущую скорость
            disp.Invoke(methodsDict["GetCurSpeed"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);
            Console.WriteLine("Current speed: " + result.ToString());

            // Получаем текущее качество
            disp.Invoke(methodsDict["GetCurQuality"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);
            Console.WriteLine("Current quality: " + result.ToString());

            // Выводим информацию об объекте
            disp.Invoke(methodsDict["DisplayStats"], guid, 1, wFlags, param, out result, pExcepInfo, puArgErr);

            Console.ReadKey();
        }
Exemplo n.º 22
0
 private static bool IsSet(ComTypes.INVOKEKIND invokeKind)
 {
     return(invokeKind == ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF);
 }
Exemplo n.º 23
0
        unsafe void NativeMethods.IDispatch.Invoke(int dispid, ref Guid riid, int lcid, System.Runtime.InteropServices.ComTypes.INVOKEKIND wFlags, ref System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, IntPtr pvarResult, IntPtr pExcepInfo, IntPtr puArgErr)
        {
            ComEventsMethod method = this.FindMethod(dispid);

            if (method == null)
            {
                return;
            }
            object[] args       = new object[pDispParams.cArgs];
            int[]    numArray   = new int[pDispParams.cArgs];
            bool[]   flagArray  = new bool[pDispParams.cArgs];
            Variant *variantPtr = (Variant *)(void *)pDispParams.rgvarg;
            int *    numPtr     = (int *)(void *)pDispParams.rgdispidNamedArgs;
            int      index1;

            for (index1 = 0; index1 < pDispParams.cNamedArgs; ++index1)
            {
                int      index2  = numPtr[index1];
                Variant *variant = ComEventsSink.GetVariant(variantPtr + index1);
                args[index2]      = variant->ToObject();
                flagArray[index2] = true;
                numArray[index2]  = !variant->IsByRef ? -1 : index1;
            }
            int index3 = 0;

            for (; index1 < pDispParams.cArgs; ++index1)
            {
                while (flagArray[index3])
                {
                    ++index3;
                }
                Variant *variant = ComEventsSink.GetVariant(variantPtr + (pDispParams.cArgs - 1 - index1));
                args[index3]     = variant->ToObject();
                numArray[index3] = !variant->IsByRef ? -1 : pDispParams.cArgs - 1 - index1;
                ++index3;
            }
            object obj = method.Invoke(args);

            if (pvarResult != IntPtr.Zero)
            {
                Marshal.GetNativeVariantForObject(obj, pvarResult);
            }
            for (int index2 = 0; index2 < pDispParams.cArgs; ++index2)
            {
                int num = numArray[index2];
                if (num != -1)
                {
                    ComEventsSink.GetVariant(variantPtr + num)->CopyFromIndirect(args[index2]);
                }
            }
        }