public unsafe static DispatchID GetNameDispId(IDispatch obj)
        {
            DispatchID dispid = DispatchID.UNKNOWN;

            string[] names = null;

            ComNativeDescriptor cnd = ComNativeDescriptor.Instance;
            bool succeeded          = false;

            // first try to find one with a valid value
            cnd.GetPropertyValue(obj, "__id", ref succeeded);

            if (succeeded)
            {
                names = new string[] { "__id" };
            }
            else
            {
                cnd.GetPropertyValue(obj, DispatchID.Name, ref succeeded);
                if (succeeded)
                {
                    dispid = DispatchID.Name;
                }
                else
                {
                    cnd.GetPropertyValue(obj, "Name", ref succeeded);
                    if (succeeded)
                    {
                        names = new string[] { "Name" };
                    }
                }
            }

            // now get the dispid of the one that worked...
            if (names != null)
            {
                DispatchID pDispid = DispatchID.UNKNOWN;
                Guid       g       = Guid.Empty;
                HRESULT    hr      = obj.GetIDsOfNames(&g, names, 1, Kernel32.GetThreadLocale(), &pDispid);
                if (hr.Succeeded())
                {
                    dispid = pDispid;
                }
            }

            return(dispid);
        }
Beispiel #2
0
        public unsafe void IDispatch_GetIDsOfNames_Invoke_Success()
        {
            using var image = new Bitmap(16, 32);
            IPictureDisp picture  = MockAxHost.GetIPictureDispFromPicture(image);
            IDispatch    dispatch = (IDispatch)picture;

            Guid riid      = Guid.Empty;
            var  rgszNames = new string[] { "Width", "Other" };
            var  rgDispId  = new DispatchID[rgszNames.Length];

            fixed(DispatchID *pRgDispId = rgDispId)
            {
                HRESULT hr = dispatch.GetIDsOfNames(&riid, rgszNames, (uint)rgszNames.Length, Kernel32.GetThreadLocale(), pRgDispId);

                Assert.Equal(HRESULT.S_OK, hr);
                Assert.Equal(new string[] { "Width", "Other" }, rgszNames);
                Assert.Equal(new DispatchID[] { (DispatchID)4, DispatchID.UNKNOWN }, rgDispId);
            }
        }
Beispiel #3
0
        private static bool HasDISPID(IDispatch dispatch, string funcName, out int dispID, bool throwOnError)
        {
            Guid guid = Guid.Empty;

            string[] names   = new string[] { funcName };
            int[]    dispIds = new int[] { -1 };
            int      hResult = dispatch.GetIDsOfNames(ref guid, names, names.Length, 0, dispIds);

            if (dispIds[0] != -1 && hResult == VSConstants.S_OK)
            {
                dispID = dispIds[0];

                return(true);
            }
            if (throwOnError)
            {
                Marshal.ThrowExceptionForHR(hResult);
            }
            dispID = -1;
            return(false);
        }
Beispiel #4
0
        // Source: https://github.com/dotnet/corefx/issues/19731
        static int GetDispId(IDispatch dispatchObject, string methodName)
        {
            int[] dispIds   = new int[1];
            Guid  emtpyRiid = Guid.Empty;
            int   hr        = dispatchObject.GetIDsOfNames(
                emtpyRiid,
                new string[] { methodName },
                1,
                0,
                dispIds);

            if ((uint)hr == 0x80020006)
            {
                return(-1);                        //DISP_E_UNKNOWNNAME
            }
            else if (hr != 0)
            {
                throw Marshal.GetExceptionForHR(hr);
            }

            return(dispIds[0]);
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            IDispatch disp = (IDispatch)(new Printer());

            int a = 0;

            disp.GetTypeInfoCount(out a);
            var id = new int[6];

            disp.GetIDsOfNames(new Guid(), new string[] { "SetPetName", "DisplayStats", "SetMaxSpeed", "GetMaxSpeed", "GetCurSpeed", "SpeedUp" },
                               6, 1, id);

            var pParam = Marshal.AllocCoTaskMem(15);

            Marshal.GetNativeVariantForObject("HP", pParam);
            object res = 0;

            System.Runtime.InteropServices.ComTypes.DISPPARAMS param = new System.Runtime.InteropServices.ComTypes.DISPPARAMS()
            {
                cArgs             = 1,
                cNamedArgs        = 0,
                rgdispidNamedArgs = IntPtr.Zero,
                rgvarg            = pParam
            };
            disp.Invoke(id[0], new Guid(), 1, new System.Runtime.InteropServices.ComTypes.INVOKEKIND(), param, out res, new IntPtr(), new IntPtr());
            Marshal.GetNativeVariantForObject("20", pParam);
            param.rgvarg = pParam;
            disp.Invoke(id[2], new Guid(), 1, new System.Runtime.InteropServices.ComTypes.INVOKEKIND(), param, out res, new IntPtr(), new IntPtr());
            disp.Invoke(id[1], new Guid(), 1, new System.Runtime.InteropServices.ComTypes.INVOKEKIND(), param, out res, new IntPtr(), new IntPtr());
            disp.Invoke(id[4], new Guid(), 1, new System.Runtime.InteropServices.ComTypes.INVOKEKIND(), param, out res, new IntPtr(), new IntPtr());
            Console.WriteLine("Cur speed = " + res.ToString());
            disp.Invoke(id[5], new Guid(), 1, new System.Runtime.InteropServices.ComTypes.INVOKEKIND(), param, out res, new IntPtr(), new IntPtr());
            disp.Invoke(id[4], new Guid(), 1, new System.Runtime.InteropServices.ComTypes.INVOKEKIND(), param, out res, new IntPtr(), new IntPtr());
            Console.WriteLine("Cur speed = " + res.ToString());

            Console.ReadKey();
        }
Beispiel #6
0
        private static bool IsArray(object jsonResult, out object[] elements)
        {
            IDispatch dispatch = jsonResult as IDispatch;

            if (dispatch == null)
            {
                elements = null;
                return(false);
            }

            int  length  = -1;
            Guid iidNull = Guid.Empty;

            int[] ids = new int[1];
            if (0 == dispatch.GetIDsOfNames(ref iidNull, new string[] { "length" }, 1, 0, ids))
            {
                // we have "length" property. That means that this type is an array type. [Note: If the object has a length property, this might be a problem]
                length = (int)jsonResult.GetType().InvokeMember("length", BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, jsonResult, null);
            }
            else
            {
                elements = null;
                return(false);
            }

            List <object> objectList = new List <object>();

            for (int i = 0; i < length; i++)
            {
                object element = jsonResult.GetType().InvokeMember(i.ToString(), BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty, null, jsonResult, null);
                objectList.Add(element);
            }

            elements = objectList.ToArray();
            return(true);
        }
Beispiel #7
0
        private static int GetDispIDForName(this IDispatch dispatch, string name)
        {
            var dispids = new int[1];
            var names   = new[] { name };

            if (HResult.Succeeded(dispatch.GetIDsOfNames(ref iid, names, 1, 0, dispids)))
            {
                return(dispids[0]);
            }

            if (name.IsDispIDName(out dispids[0]))
            {
                return(dispids[0]);
            }

            var member = dispatch.GetMembers().FirstOrDefault(testMember => testMember.Name == name);

            if (member == null)
            {
                throw new MissingMemberException(MiscHelpers.FormatInvariant("The object has no property named '{0}'", name));
            }

            return(member.DispID);
        }
Beispiel #8
0
        private string GetName(IDispatch dispatch)
        {
            string theName = null;

            if (nameProperty != null)
            {
                IntPtr ptrDispatch = Marshal.GetIDispatchForObject(dispatch);
                try
                {
                    if (ptrDispatch != IntPtr.Zero)
                    {
                        object typedObject = Marshal.GetTypedObjectForIUnknown(ptrDispatch, comType);
                        if (typedObject != null)
                        {
                            theName = (string)nameProperty.GetValue(typedObject, null);
                        }
                    }
                }
                catch
                {
                    theName = null;
                }
                finally
                {
                    if (ptrDispatch != IntPtr.Zero)
                    {
                        Marshal.Release(ptrDispatch);
                        ptrDispatch = IntPtr.Zero;
                    }
                }
            }
            if (theName == null)
            {
                Guid     guid    = Guid.Empty;
                string[] names   = new string[] { "Name" };
                int[]    dispIds = new int[] { 0 };
                dispatch.GetIDsOfNames(ref guid, names, names.Length, 0, dispIds);
                if (dispIds[0] != -1)
                {
                    ComTypes.DISPPARAMS[] dispParams = new ComTypes.DISPPARAMS[1];
                    dispParams[0].cNamedArgs        = 0;
                    dispParams[0].rgdispidNamedArgs = IntPtr.Zero;
                    dispParams[0].cArgs             = 1;
                    dispParams[0].rgvarg            = Marshal.AllocCoTaskMem(0x1000);
                    try
                    {
                        Marshal.GetNativeVariantForObject(theName, dispParams[0].rgvarg);
                        dispatch.Invoke(
                            dispIds[0],
                            ref guid,
                            CultureInfo.CurrentCulture.LCID,
                            (short)ComTypes.INVOKEKIND.INVOKE_PROPERTYGET,
                            dispParams,
                            null,
                            null,
                            null);
                        object retValue = Marshal.GetObjectForNativeVariant(dispParams[0].rgvarg);
                        if (retValue is string)
                        {
                            theName = (string)retValue;
                        }
                    }
                    finally
                    {
                        Marshal.FreeCoTaskMem(dispParams[0].rgvarg);
                        dispParams[0].rgvarg = IntPtr.Zero;
                    }
                }
            }
            return(theName);
        }
Beispiel #9
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();
        }
Beispiel #10
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();
        }