Ejemplo n.º 1
0
        public static T CreateFromDll <T>(string dllName, Guid mpaguid)
        {
            if (String.IsNullOrEmpty(dllName))
            {
                throw new ArgumentNullException("dllName");
            }

            //Get a classFactory for our classID
            IClassFactory classFactory = ComHelper.GetClassFactory(dllName, mpaguid);

            if (classFactory == null)
            {
                throw new COMException(String.Format("Can't create ClassFactory from '{0}", dllName));
            }

            //And create an object-instance using that class factory
            Guid   iGUID = typeof(T).GUID;
            Object obj;

            try
            {
                Marshal.ThrowExceptionForHR(classFactory.CreateInstance(null, ref iGUID, out obj));
                return((T)obj);
            }
            finally { Marshal.ReleaseComObject(classFactory); }
        }
Ejemplo n.º 2
0
        private static IFilter LoadFilterFromDll(string ext, string dllName, string filterPersistClass)
        {
            Type   T;
            object obj;

            Cache_V2.TryGetValue(ext, out T);
            if (null == T)
            {
                T = Type.GetTypeFromCLSID(new Guid(filterPersistClass));
            }
            if (null != T)
            {
                Cache_V2[ext] = T;
                //obj = T.InvokeMember("_ctor", BindingFlags.CreateInstance, null, null, null);
                obj = Activator.CreateInstance(T);
            }
            else
            {
                IClassFactory classFactory = GetClassFactory(ext, dllName, filterPersistClass);
                if (null == classFactory)
                {
                    return(null);
                }
                var IFilterGUID = new Guid(Constants.IFilterGUID);
                classFactory.CreateInstance(null, ref IFilterGUID, out obj);
            }
            //var mixedFilter = Marshal.GetTypedObjectForIUnknown(ptr, typeof(MixedIFilterClass)) as MixedIFilterClass;
            var mixedFilter = (MixedIFilterClass)Marshal.CreateWrapperOfType(obj, typeof(MixedIFilterClass));

            mixedFilter.InternalObj = obj;
            return((IFilter)mixedFilter);
        }
Ejemplo n.º 3
0
        protected override void Initialize(IGraphBuilder pGraphBuilder, IntPtr hMediaWindow)
        {
            object factoryObject   = null;
            object presenterObject = null;

            try
            {
                int hr = ClassFactory.GetEvrPresenterClassFactory(ref CLSID_CustomEVRPresenter, ref ClassFactory.IID_ClassFactory, out factoryObject);
                Marshal.ThrowExceptionForHR(hr);

                IClassFactory factory = (IClassFactory)factoryObject;

                var iidPresenter = typeof(IMFVideoPresenter).GUID;
                hr = factory.CreateInstance(null, ref iidPresenter, out presenterObject);
                Marshal.ThrowExceptionForHR(hr);

                IMFVideoPresenter presenter = (IMFVideoPresenter)presenterObject;

                IMFVideoRenderer renderer = (IMFVideoRenderer)BaseFilter; // will be released when IBaseFilter is released
                renderer.InitializeRenderer(null, presenter);

                IMFGetService pMFGetService = (IMFGetService)BaseFilter; // will be released when IBaseFilter is released
                object        o;
                var           serviceId = ServiceID.EnhancedVideoRenderer;
                var           iidImfVideoDisplayControl = typeof(IMFVideoDisplayControl).GUID;
                Marshal.ThrowExceptionForHR(pMFGetService.GetService(ref serviceId, ref iidImfVideoDisplayControl, out o));
                _pMFVideoDisplayControl = (IMFVideoDisplayControl)o;

                _pMFVideoDisplayControl.SetVideoWindow(hMediaWindow);
                _pMFVideoDisplayControl.SetAspectRatioMode(MFVideoAspectRatioMode.MFVideoARMode_None);

                _pvpPresenterConfig = (IPvpPresenterConfig)presenterObject;
                _pvpPresenterConfig.SetBufferCount(PRESENTER_BUFFER_COUNT);

                _pvpPresenterHook.HookUp(presenterObject);

                // as EVR requests IMFVideoDisplayControl from the presenter and our custom presenter implements IPvpPresenter and IPvpPresenterConfig
                // presenterObject and _pMFVideoDisplayControl point to the same RCW

                presenterObject = null; // we will release the presenter when releasing _pMFVideoDisplayControl
            }
            catch
            {
                _pMFVideoDisplayControl = null;
                _pvpPresenterConfig     = null;
            }
            finally
            {
                if (factoryObject != null)
                {
                    Marshal.FinalReleaseComObject(factoryObject);
                }

                if (presenterObject != null)
                {
                    Marshal.FinalReleaseComObject(presenterObject);
                }
            }
        }
Ejemplo n.º 4
0
        private object GetClassInstance(Guid classguid, Guid interfguid, Guid classfactoryguid, Guid classfactory2guid)
        {
            object classinstance = null;

            // create instance via raw dll functions
            // ensures we get the real vtable
            try
            {
                if (classinstance == null)
                {
                    // Single do..while loop - to support "break;"
                    do
                    {
                        Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\{" + classguid.ToString() + "}\\InprocServer32");
                        if (rk == null)
                        {
                            break;
                        }
                        string classdllname = rk.GetValue(null).ToString();
                        IntPtr libH         = KERNEL32.LoadLibrary(classdllname);
                        if (libH == IntPtr.Zero)
                        {
                            break;
                        }
                        IntPtr factoryFunc = KERNEL32.GetProcAddress(libH, "DllGetClassObject");
                        if (factoryFunc == IntPtr.Zero)
                        {
                            break;
                        }
                        DllGetClassObjectDelegate factoryDel = (DllGetClassObjectDelegate)Marshal.GetDelegateForFunctionPointer(factoryFunc, typeof(DllGetClassObjectDelegate));
                        object classfactoryO;
                        // Try with IClassFactory first
                        factoryDel(ref classguid, ref classfactoryguid, out classfactoryO);
                        if (classfactoryO != null)
                        {
                            IClassFactory classfactory = (IClassFactory)classfactoryO;
                            classfactory.CreateInstance(null, ref interfguid, out classinstance);
                            Marshal.FinalReleaseComObject(classfactory);
                        }
                        else
                        {
                            // Now try with IClassFactory2
                            factoryDel(ref classguid, ref classfactory2guid, out classfactoryO);
                            if (classfactoryO == null)
                            {
                                break;
                            }
                            IClassFactory2 classfactory = (IClassFactory2)classfactoryO;
                            classinstance = classfactory.CreateInstance(null, interfguid);
                            Marshal.FinalReleaseComObject(classfactory);
                        }
                    } while (false);
                }
            }
            catch { }

            return(classinstance);
        }
Ejemplo n.º 5
0
        private static void CoCreateFromMsdia(Guid clsidOfServer, Guid riid, out IntPtr pvObject)
        {
            IntPtr        pClassFactory = IntPtr.Zero;
            int           hr            = DllGetClassObject(clsidOfServer, new Guid("00000001-0000-0000-C000-000000000046"), out pClassFactory);
            IClassFactory classFactory  = Marshal.GetObjectForIUnknown(pClassFactory) as IClassFactory;

            classFactory.CreateInstance(IntPtr.Zero, ref riid, out pvObject);
            Marshal.Release(pClassFactory);
            Marshal.ReleaseComObject(classFactory);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates an object from a given COM dll by a class id and a given interface
        /// </summary>
        public static bool LoadAndCreate <T>(string dllPath, out T source, out string errorMessage, Guid classId)
            where T : class
        {
            if (string.IsNullOrWhiteSpace(dllPath) && !System.IO.File.Exists(dllPath))
            {
                source = null;

                errorMessage = "Path to a dll not found - " + dllPath;
                return(false);
            }

            IntPtr dllHandle = LoadLibrary(dllPath);

            if (dllHandle == IntPtr.Zero)
            {
                source       = null;
                errorMessage = "Could not load library " + dllPath;
                return(false);
            }

            try
            {
                IntPtr fp = GetProcAddress(dllHandle, "DllGetClassObject");
                DllGetClassObjectFunction getClassObj = (DllGetClassObjectFunction)Marshal.GetDelegateForFunctionPointer(fp, typeof(DllGetClassObjectFunction));
                object c;
                Guid   diaSourceClassGuid = classId;

                Guid classFactoryGuid = typeof(IClassFactory).GUID;
                int  hr = getClassObj(ref diaSourceClassGuid, ref classFactoryGuid, out c);

                if (hr != 0)
                {
                    throw new COMException("Could not get object for CLSID " + classId, hr);
                }

                IClassFactory factory   = c as IClassFactory;
                T             diaSource = (T)factory.CreateInstance(null, typeof(T).GUID);
                // the cast to T increased the reference count
                //int cnt = Marshal.ReleaseComObject(diaSource);
                //if (cnt != 1)
                //    Console.WriteLine("diaSource.RefCount not 1, but {0}", cnt);
                source       = diaSource;
                errorMessage = "";
                return(true);
            }
            catch (Exception e)
            {
                errorMessage = string.Format("Could not get {0} from the library {1}. Details: {2}", typeof(T).Name, dllPath, e);
                source       = null;
                return(false);
            }
        }
Ejemplo n.º 7
0
        public static IDiaDataSource CreateInstance()
        {
            if (DiaSourceFactory == null)
            {
                var DiaSourceClassGuid = new Guid("e6756135-1e65-4d17-8576-610761398c3c");
                var IID_IClassFactory  = typeof(IClassFactory).GUID;
                DiaSourceFactory = (IClassFactory)DllGetClassObject(ref DiaSourceClassGuid, ref IID_IClassFactory);
            }

            var IID_IDiaDataSource = typeof(IDiaDataSource).GUID;

            return((IDiaDataSource)DiaSourceFactory.CreateInstance(null, IID_IDiaDataSource));
        }
Ejemplo n.º 8
0
        public static T CreateInstance <T>(IClassFactory classFactory, Type interfaceType) where T : class
        {
            object obj;
            var    wbGuid = interfaceType.GUID;

            classFactory.CreateInstance(null, ref wbGuid, out obj);
            var res = obj as T;

            if (res == null)
            {
                throw new Exception("res == null");
            }
            return(res);
        }
Ejemplo n.º 9
0
        public static object CreatePassword()
        {
            object classObject;

            DllGetClassObject(ref ProgID_IPassword, ref IID_IClassFactory, out classObject);

            uint dwRegister;

            CoRegisterClassObject(ref IID_IClassFactory, classObject, 0, 0, out dwRegister);

            IClassFactory classFactory = classObject as IClassFactory;
            object        password     = classFactory.CreateInstance(null, ref IID_IUnknown);

            return(password);
        }
Ejemplo n.º 10
0
        private static object CreateInstanceFromFileInternal(string filePath, Guid classId, Guid iid)
        {
            IntPtr        hModule, getClassObjectPtr, classFactoryPtr = IntPtr.Zero;
            IClassFactory classFactory = null;

            try
            {
                hModule = NativeMethods.LoadLibrary(filePath);
                if (hModule == IntPtr.Zero)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                getClassObjectPtr = NativeMethods.GetProcAddress(hModule, "DllGetClassObject");
                if (getClassObjectPtr == IntPtr.Zero)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                DllGetClassObjectSig DllGetClassObject = (DllGetClassObjectSig)Marshal.GetDelegateForFunctionPointer(getClassObjectPtr, typeof(DllGetClassObjectSig));

                HResult hr = DllGetClassObject(classId, typeof(IClassFactory).GUID, out classFactoryPtr);
                hr.ThrowExceptionOnError();

                classFactory = (IClassFactory)Marshal.GetObjectForIUnknown(classFactoryPtr);

                object result;

                hr = classFactory.CreateInstance(null, iid, out result);
                hr.ThrowExceptionOnError();

                return(result);
            }
            finally
            {
                if (classFactory != null)
                {
                    int i = Marshal.ReleaseComObject(classFactory);
                    classFactory = null;
                }

                if (classFactoryPtr != IntPtr.Zero)
                {
                    int i = Marshal.Release(classFactoryPtr);
                    classFactoryPtr = IntPtr.Zero;
                }
            }
        }
Ejemplo n.º 11
0
        private static IFilter LoadFilterFromDll(string dllName, string filterPersistClass)
        {
            IClassFactory classFactory = ComHelper.GetClassFactory(dllName, filterPersistClass);

            if (classFactory == null)
            {
                return(null);
            }


            Guid   IFilterGUID = new Guid("89BCB740-6119-101A-BCB7-00DD010655AF");
            Object obj;

            classFactory.CreateInstance(null, ref IFilterGUID, out obj);
            return(obj as IFilter);
        }
Ejemplo n.º 12
0
        private static IFilter LoadFilterFromDll(string dllName, string filterPersistClass)
        {
            //Get a classFactory for our classID
            IClassFactory classFactory = ComHelper.GetClassFactory(dllName, filterPersistClass);

            if (classFactory == null)
            {
                return(null);
            }

            //And create an IFilter instance using that class factory
            Object obj;

            classFactory.CreateInstance(null, ref IFilterGUID, out obj);
            return(obj as IFilter);
        }
Ejemplo n.º 13
0
            private static DocHelper.IFilter LoadFilterFromDll(string dllName, string filterPersistClass)
            {
                //Get a classFactory for our classID
                IClassFactory classFactory = ComHelper.GetClassFactory(dllName, filterPersistClass);

                if (classFactory == null)
                {
                    return(null);
                }

                //And create an DocHelper.IFilter instance using that class factory
                Guid   IFilterGUID = new Guid("89BCB740-6119-101A-BCB7-00DD010655AF");
                Object obj;

                classFactory.CreateInstance(null, ref IFilterGUID, out obj);
                return(obj as DocHelper.IFilter);
            }
Ejemplo n.º 14
0
        /// <summary>
        /// Load a COM object from the supplied assembly using the supplied class ID and interface ID.
        /// </summary>
        /// <param name="pathToNativeAssembly">Path to assembly</param>
        /// <param name="clsid">Class ID</param>
        /// <param name="iid">Interface ID</param>
        /// <returns>Loaded COM instance</returns>
        public static object CreateInstanceFrom(
            string pathToNativeAssembly,
            Guid clsid,
            Guid iid)
        {
            if (string.IsNullOrEmpty(pathToNativeAssembly))
            {
                throw new ArgumentNullException(nameof(pathToNativeAssembly));
            }

            IntPtr nativeDllPointer = NativeMethods.LoadLibraryEx(
                pathToNativeAssembly,
                IntPtr.Zero,
                NativeMethods.LoadLibraryFlags.LOAD_WITH_ALTERED_SEARCH_PATH);

            if (nativeDllPointer == IntPtr.Zero)
            {
                throw new DllNotFoundException(pathToNativeAssembly);
            }

            IntPtr dllGetClassObjectFunctionPointer = NativeMethods.GetProcAddress(nativeDllPointer, "DllGetClassObject");

            if (dllGetClassObjectFunctionPointer == IntPtr.Zero)
            {
                throw new NullReferenceException("DllGetClassObject");
            }

#pragma warning disable 618
            DllGetClassObjectDelegate dllGetClassObject = (DllGetClassObjectDelegate)Marshal.GetDelegateForFunctionPointer(
#pragma warning restore 618
                dllGetClassObjectFunctionPointer,
                typeof(DllGetClassObjectDelegate));

            object ppv      = null;
            object instance = null;
            dllGetClassObject(clsid, typeof(IClassFactory).GetTypeInfo().GUID, out ppv);

            IClassFactory factory = ppv as IClassFactory;
            if (factory != null)
            {
                instance = factory.CreateInstance(null, iid);
                Marshal.ReleaseComObject(factory);
            }

            return(instance);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Loads an COM .dll and creates an instance of the given Interface with IID <paramref name="interfaceId"/>.
        /// </summary>
        /// <param name="dllName">Filename of a .dll or .ax component</param>
        /// <param name="interfaceId">Interface to create an object instance for</param>
        /// <param name="useAssemblyRelativeLocation">Combine the given file name to a full path</param>
        /// <returns>Instance or <c>null</c></returns>
        public static IBaseFilter LoadFilterFromDll(string dllName, Guid interfaceId, bool useAssemblyRelativeLocation = false)
        {
            // Get a ClassFactory for our classID
            string        dllPath      = useAssemblyRelativeLocation ? BuildAssemblyRelativePath(dllName) : dllName;
            IClassFactory classFactory = ComHelper.GetClassFactory(dllPath, interfaceId);

            if (classFactory == null)
            {
                return(null);
            }

            // And create an IFilter instance using that class factory
            Guid   baseFilterGuid = typeof(IBaseFilter).GUID;
            object obj;

            classFactory.CreateInstance(null, ref baseFilterGuid, out obj);
            return(obj as IBaseFilter);
        }
Ejemplo n.º 16
0
 private void btnCreate_Click(object sender, EventArgs e)
 {
     try
     {
         IClassFactory factory = (IClassFactory)m_pObject;
         object        new_object;
         Guid          IID_IUnknown        = COMInterfaceEntry.IID_IUnknown;
         Dictionary <string, string> props = new Dictionary <string, string>();
         props.Add("Name", m_objName);
         factory.CreateInstance(null, ref IID_IUnknown, out new_object);
         ObjectInformation view = new ObjectInformation(m_registry, m_objName, new_object,
                                                        props, m_registry.GetInterfacesForObject(new_object));
         Program.GetMainForm().HostControl(view);
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        private static IFilter LoadFilterFromDll(string dllName, string filterPersistClass)
        {
            //Get a classFactory for our classID
            IClassFactory classFactory = ComHelper.GetClassFactory(dllName, filterPersistClass);

            if (classFactory == null)
            {
                return(null);
            }

            //And create an IFilter instance using that class factory
            // http://msdn2.microsoft.com/en-us/library/aa965717.aspx
            // The first identifies all filters' persistent handler, IID_IFilter, which is {89BCB740-6119-101A-BCB7-00DD010655AF}. This CLSID is constant for all filters that implement IFilter.
            Guid   IFilterGUID = new Guid("89BCB740-6119-101A-BCB7-00DD010655AF");
            Object obj;

            classFactory.CreateInstance(null, ref IFilterGUID, out obj);
            return(obj as IFilter);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Create a new EVR video presenter
        /// </summary>
        /// <returns></returns>
        public static EvrPresenter CreateNew(IMFActivate activate)
        {
            object comObject = null;

            int hr = 0;

            /* Our exception var we use to hold the exception
             * until we need to throw it (after clean up) */
            Exception exception = null;

            /* A COM object we query form our native library */
            IClassFactory factory = null;

            /* Create our 'helper' class */
            var evrPresenter = new EvrPresenter();

            /* Call the DLL export to create the class factory */
            if (ProcessBits == 32)
            {
                //activate.SetGUID(MFAttributesClsid.MF_ACTIVATE_CUSTOM_VIDEO_PRESENTER_CLSID, EVR_PRESENTER_CLSID);
                hr = DllGetClassObject32(EVR_PRESENTER_CLSID, IUNKNOWN_GUID, out comObject);
                //activate.SetUnknown(MFAttributesClsid.MF_ACTIVATE_CUSTOM_VIDEO_PRESENTER_ACTIVATE, evrPresenter as IMFActivate);
                //activate.ActivateObject(EVR_PRESENTER_CLSID, out comObject);
            }
            else if (ProcessBits == 64)
            {
                activate.SetGUID(MFAttributesClsid.MF_ACTIVATE_CUSTOM_VIDEO_PRESENTER_CLSID, EVR_PRESENTER_CLSID);
                hr = DllGetClassObject64(EVR_PRESENTER_CLSID, IUNKNOWN_GUID, out comObject);
            }
            else
            {
                exception = new Exception(string.Format("{0} bit processes are unsupported", ProcessBits));
                goto bottom;
            }

            /* Check if our call to our DLL failed */
            if (hr != 0 || comObject == null)
            {
                exception = new COMException("Could not create a new class factory.", hr);
                goto bottom;
            }

            /* Cast the COM object that was returned to a COM interface type */
            factory = comObject as IClassFactory;

            if (factory == null)
            {
                exception = new Exception("Could not QueryInterface for the IClassFactory interface");
                goto bottom;
            }

            /* Get the GUID of the IMFVideoPresenter */
            Guid   guidActivate = typeof(IMFActivate).GUID;
            object comActObject;

            /* Creates a new instance of the IMFVideoPresenter */
            factory.CreateInstance(null, ref guidActivate, out comActObject);

            // Set the Unknown IMFAttribute to ActivateObject
            activate.SetUnknown(MFAttributesClsid.MF_ACTIVATE_CUSTOM_VIDEO_PRESENTER_ACTIVATE, comActObject);

            /* QueryInterface for the IMFVideoPresenter */
            var presenter = comActObject as IMFVideoPresenter;

            /* QueryInterface for our callback registration interface */
            var registerCb = comActObject as IEVRPresenterRegisterCallback;

            if (registerCb == null)
            {
                exception = new Exception("Could not QueryInterface for IEVRPresenterRegisterCallback");
                goto bottom;
            }

            /* Register the callback to the 'helper' class we created */
            registerCb.RegisterCallback(evrPresenter);

            /* Populate the IMFVideoPresenter */
            evrPresenter.VideoPresenter = presenter;

bottom:

            if (factory != null)
            {
                Marshal.FinalReleaseComObject(factory);
            }

            if (exception != null)
            {
                throw exception;
            }

            return(evrPresenter);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Create a new EVR video presenter
        /// </summary>
        /// <returns></returns>
        public static WindowShadow CreateNew()
        {
            object comObject;

            int hr;

            /* Our exception var we use to hold the exception
             * until we need to throw it (after clean up) */
            Exception exception = null;

            /* A COM object we query form our native library */
            IClassFactory factory = null;

            /* Create our 'helper' class */
            var windowShadow = new WindowShadow();

            /* Call the DLL export to create the class factory */
            if (ProcessBits == 32)
            {
                hr = DllGetClassObject32(WINDOW_SHADOW_CLSID, IUNKNOWN_GUID, out comObject);
            }
            else if (ProcessBits == 64)
            {
                hr = DllGetClassObject64(WINDOW_SHADOW_CLSID, IUNKNOWN_GUID, out comObject);
            }
            else
            {
                exception = new Exception(string.Format("{0} bit processes are unsupported", ProcessBits));
                goto bottom;
            }

            /* Check if our call to our DLL failed */
            if (hr != 0 || comObject == null)
            {
                exception = new COMException("Could not create a new class factory.", hr);
                goto bottom;
            }

            /* Cast the COM object that was returned to a COM interface type */
            factory = comObject as IClassFactory;

            if (factory == null)
            {
                exception = new Exception("Could not QueryInterface for the IClassFactory interface");
                goto bottom;
            }

            /* Get the GUID of the class */
            Guid guid = typeof(IWindowShadow).GUID;

            /* Creates a new instance of the IMFVideoPresenter */
            factory.CreateInstance(null, ref guid, out comObject);

            /* QueryInterface for the IMFVideoPresenter */
            var shadower = comObject as IWindowShadow;

            /* Populate the shadower */
            windowShadow.Shadower = shadower;

bottom:

            if (factory != null)
            {
                Marshal.FinalReleaseComObject(factory);
            }

            if (exception != null)
            {
                throw exception;
            }

            return(windowShadow);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Load the merge object directly from a local mergemod.dll without going through COM registration.
        /// </summary>
        /// <returns>Merge interface.</returns>
        internal static IMsmMerge2 GetMsmMerge()
        {
            IClassFactory classFactory = (IClassFactory)MergeModGetClassObject(typeof(MsmMerge2).GUID, typeof(IClassFactory).GUID);

            return((IMsmMerge2)classFactory.CreateInstance(IntPtr.Zero, typeof(IMsmMerge2).GUID));
        }
Ejemplo n.º 21
0
        public static unsafe void Query(ComClassInfo cci)
        {
            Guid classguid = cci.ClassType.GUID;

            Guid   interfguid        = cci.InterfaceType.GUID;
            Guid   classfactoryguid  = typeof(IClassFactory).GUID;
            Guid   classfactory2guid = typeof(IClassFactory2).GUID;
            object classinstance     = null;

#if false
            // create an instance via .NET built-in functionality
            // vtable might be hijacked by rpcrt4.dll
            classinstance = cci.ClassType.InvokeMember("", BindingFlags.CreateInstance, null, null, null);
#endif
#if false
            // create via ole-convenience-function
            // vtable might be hijacked by rpcrt4.dll
            OLE32.CoCreateInstance(ref classguid, null, 1 + 4, ref interfguid, out classinstance);
#endif
#if false
            // create via ole-functions
            // vtable might be hijacked by rpcrt4.dll
            try
            {
                if (classinstance == null)
                {
                    object classfactoryO;
                    OLE32.CoGetClassObject(ref classguid, 1 + 4, 0, ref classfactoryguid, out classfactoryO);
                    IClassFactory classfactory = (IClassFactory)classfactoryO;
                    classfactory.CreateInstance(null, ref interfguid, out classinstance);
                    Marshal.FinalReleaseComObject(classfactory);
                }
            }
            catch { }
            try
            {
                if (classinstance == null)
                {
                    object classfactoryO;
                    OLE32.CoGetClassObject(ref classguid, 1 + 4, 0, ref classfactoryguid, out classfactoryO);
                    IClassFactory2 classfactory = (IClassFactory2)classfactoryO;
                    classinstance = classfactory.CreateInstance(null, interfguid);
                    Marshal.FinalReleaseComObject(classfactory);
                }
            }
            catch { }
            if (classinstance == null)
            {
                // Error...
            }
#endif
#if true
            // create via raw dll functions
            // no chance for other people to hijack the vtable
            try
            {
                do
                {
                    RegistryKey rk = Registry.ClassesRoot.OpenSubKey("CLSID\\{" + classguid + "}\\InprocServer32");
                    if (rk == null)
                    {
                        break;
                    }
                    string classdllname = rk.GetValue(null).ToString();
                    IntPtr libH         = KERNEL32.LoadLibrary(classdllname);
                    if (libH == IntPtr.Zero)
                    {
                        break;
                    }
                    IntPtr factoryFunc = KERNEL32.GetProcAddress(libH, "DllGetClassObject");
                    if (factoryFunc == IntPtr.Zero)
                    {
                        break;
                    }
                    var factoryDel =
                        (DllGetClassObjectDelegate)
                        Marshal.GetDelegateForFunctionPointer(factoryFunc, typeof(DllGetClassObjectDelegate));
                    object classfactoryO;
                    factoryDel(ref classguid, ref classfactoryguid, out classfactoryO);
                    if (classfactoryO == null)
                    {
                        break;
                    }
                    var classfactory = (IClassFactory)classfactoryO;
                    classfactory.CreateInstance(null, ref interfguid, out classinstance);
                    Marshal.FinalReleaseComObject(classfactory);
                } while (false);
            }
            catch
            {
            }
            try
            {
                if (classinstance == null)
                {
                    do
                    {
                        RegistryKey rk = Registry.ClassesRoot.OpenSubKey("CLSID\\{" + classguid + "}\\InprocServer32");
                        if (rk == null)
                        {
                            break;
                        }
                        string classdllname = rk.GetValue(null).ToString();
                        IntPtr libH         = KERNEL32.LoadLibrary(classdllname);
                        if (libH == IntPtr.Zero)
                        {
                            break;
                        }
                        IntPtr factoryFunc = KERNEL32.GetProcAddress(libH, "DllGetClassObject");
                        if (factoryFunc == IntPtr.Zero)
                        {
                            break;
                        }
                        var factoryDel =
                            (DllGetClassObjectDelegate)
                            Marshal.GetDelegateForFunctionPointer(factoryFunc, typeof(DllGetClassObjectDelegate));
                        object classfactoryO;
                        factoryDel(ref classguid, ref classfactory2guid, out classfactoryO);
                        if (classfactoryO == null)
                        {
                            break;
                        }
                        var classfactory = (IClassFactory2)classfactoryO;
                        classinstance = classfactory.CreateInstance(null, interfguid);
                        Marshal.FinalReleaseComObject(classfactory);
                    } while (false);
                }
            }
            catch
            {
            }
            if (classinstance == null)
            {
                // Error...
            }
#endif

            IntPtr interfaceIntPtr = Marshal.GetComInterfaceForObject(classinstance, cci.InterfaceType);
            var    interfaceRawPtr = (int ***)interfaceIntPtr.ToPointer();
            // get vtable
            int **vTable = *interfaceRawPtr;
            // get com-slot-number (vtable-index) of function X
            // get function-address from vtable
            int  mi_vto = Marshal.GetComSlotForMethodInfo(cci.Method);
            int *faddr  = vTable[mi_vto];
            cci.MFunctionPointer = new IntPtr(faddr);
            // release intptr
            Marshal.Release(interfaceIntPtr);
            Marshal.FinalReleaseComObject(classinstance);
        }
Ejemplo n.º 22
0
        internal IProxyProvider GetProxyProvider()
        {
            if (null == monikerSupportLibrary)
            {
                lock (this)
                {
                    if (null == monikerSupportLibrary)
                    {
                        getCODelegate = null;
                        using (RegistryHandle regKey = RegistryHandle.GetCorrectBitnessHKLMSubkey((IntPtr.Size == 8), ServiceModelInstallStrings.WinFXRegistryKey))
                        {
                            string            file        = regKey.GetStringValue(ServiceModelInstallStrings.RuntimeInstallPathName).TrimEnd('\0') + "\\" + fileName;
                            SafeLibraryHandle tempLibrary = UnsafeNativeMethods.LoadLibrary(file);
                            tempLibrary.DoNotFreeLibraryOnRelease();

                            monikerSupportLibrary = tempLibrary;
                            if (monikerSupportLibrary.IsInvalid)
                            {
                                monikerSupportLibrary.SetHandleAsInvalid();
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ServiceMonikerSupportLoadFailed(file));
                            }
                        }
                    }
                }
            }

            if (null == getCODelegate)
            {
                lock (this)
                {
                    if (null == getCODelegate)
                    {
                        try
                        {
                            IntPtr procaddr = UnsafeNativeMethods.GetProcAddress(monikerSupportLibrary, functionName);
                            getCODelegate = (DelegateDllGetClassObject)Marshal.GetDelegateForFunctionPointer(procaddr, typeof(DelegateDllGetClassObject));
                        }
                        catch (Exception e)
                        {
                            if (Fx.IsFatal(e))
                            {
                                throw;
                            }

                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ComPlusProxyProviderException(SR.GetString(SR.FailedProxyProviderCreation), e));
                        }
                    }
                }
            }

            IClassFactory  cf            = null;
            IProxyProvider proxyProvider = null;

            try
            {
                getCODelegate(ClsidProxyInstanceProvider, typeof(IClassFactory).GUID, ref cf);

                proxyProvider = cf.CreateInstance(null, typeof(IProxyProvider).GUID) as IProxyProvider;
                Thread.MemoryBarrier();
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ComPlusProxyProviderException(SR.GetString(SR.FailedProxyProviderCreation), e));
            }
            finally
            {
                if (null != cf)
                {
                    Marshal.ReleaseComObject(cf);
                    cf = null;
                }
            }

            return(proxyProvider);
        }
Ejemplo n.º 23
0
        public static object IldbCoCreateInstance(System.Guid clsid, System.Guid iid)
        {
            IClassFactory fac = (IClassFactory)DllGetClassObject(clsid, typeof(IClassFactory).GUID);

            return(fac.CreateInstance(null, iid));
        }
        internal IProxyProvider GetProxyProvider()
        {
            if (this.monikerSupportLibrary == null)
            {
                lock (this)
                {
                    if (this.monikerSupportLibrary == null)
                    {
                        this.getCODelegate = null;
                        using (RegistryHandle handle = RegistryHandle.GetCorrectBitnessHKLMSubkey(IntPtr.Size == 8, @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client"))
                        {
                            string libFilename = handle.GetStringValue("InstallPath").TrimEnd(new char[1]) + @"\ServiceMonikerSupport.dll";
                            this.monikerSupportLibrary = UnsafeNativeMethods.LoadLibrary(libFilename);
                            this.monikerSupportLibrary.DoNotFreeLibraryOnRelease();
                            if (this.monikerSupportLibrary.IsInvalid)
                            {
                                this.monikerSupportLibrary.SetHandleAsInvalid();
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ServiceMonikerSupportLoadFailed(libFilename));
                            }
                        }
                    }
                }
            }
            if (this.getCODelegate == null)
            {
                lock (this)
                {
                    if (this.getCODelegate == null)
                    {
                        try
                        {
                            IntPtr procAddress = UnsafeNativeMethods.GetProcAddress(this.monikerSupportLibrary, "DllGetClassObject");
                            this.getCODelegate = (DelegateDllGetClassObject)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(DelegateDllGetClassObject));
                        }
                        catch (Exception exception)
                        {
                            if (Fx.IsFatal(exception))
                            {
                                throw;
                            }
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ComPlusProxyProviderException(System.ServiceModel.SR.GetString("FailedProxyProviderCreation"), exception));
                        }
                    }
                }
            }
            IClassFactory  ppv      = null;
            IProxyProvider provider = null;

            try
            {
                this.getCODelegate(ClsidProxyInstanceProvider, typeof(IClassFactory).GUID, ref ppv);
                provider = ppv.CreateInstance(null, typeof(IProxyProvider).GUID) as IProxyProvider;
                Thread.MemoryBarrier();
            }
            catch (Exception exception2)
            {
                if (Fx.IsFatal(exception2))
                {
                    throw;
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ComPlusProxyProviderException(System.ServiceModel.SR.GetString("FailedProxyProviderCreation"), exception2));
            }
            finally
            {
                if (ppv != null)
                {
                    Marshal.ReleaseComObject(ppv);
                    ppv = null;
                }
            }
            return(provider);
        }
Ejemplo n.º 25
0
        //http://www.gdcl.co.uk/2011/June/UnregisteredFilters.htm
        public object CreateObjectFromPath(string dllPath, Guid clsid, bool setSearchPath, bool comFallback)
        {
            object createdObject = null;
            IntPtr lib           = IntPtr.Zero;
            string fullDllPath   = Path.Combine(SearchPath, dllPath);

            _logger.Debug("CreateObjectFromPath: {0} - {1} - {2} - {3}", fullDllPath, clsid, setSearchPath, comFallback);

            if (File.Exists(fullDllPath) && (_preferURObjects || !comFallback))
            {
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(fullDllPath);
                _logger.Debug("Load: {0} Version: {1}", fileVersionInfo.FileDescription, fileVersionInfo.FileVersion);
                if (_libsLoaded.ContainsKey(dllPath))
                {
                    _logger.Debug("Load: {0} from cache", dllPath);
                    lib = _libsLoaded[dllPath];
                }
                else
                {
                    //some dlls have external dependancies, setting the search path to its location should assist with this
                    if (setSearchPath)
                    {
                        NativeMethods.SetDllDirectory(Path.GetDirectoryName(fullDllPath));
                    }

                    lib = NativeMethods.LoadLibrary(fullDllPath);

                    if (setSearchPath)
                    {
                        NativeMethods.SetDllDirectory(null);
                    }
                }

                if (lib != IntPtr.Zero)
                {
                    //we need to cache the handle so the COM object will work and we can clean up later
                    _libsLoaded[dllPath] = lib;
                    IntPtr fnP = NativeMethods.GetProcAddress(lib, "DllGetClassObject");
                    if (fnP != IntPtr.Zero)
                    {
                        DllGETCLASSOBJECTInvoker fn = Marshal.GetDelegateForFunctionPointer(fnP, typeof(DllGETCLASSOBJECTInvoker)) as DllGETCLASSOBJECTInvoker;

                        object pUnk = null;
                        int    hr   = fn(clsid, IID_IUnknown, out pUnk);
                        if (hr >= 0)
                        {
                            IClassFactory pCF = pUnk as IClassFactory;
                            if (pCF != null)
                            {
                                hr = pCF.CreateInstance(null, IID_IUnknown, out createdObject);
                                _logger.Debug("CreateInstance {0}: {1}", fileVersionInfo.FileDescription, hr);
                            }
                        }
                    }
                    else
                    {
                        _logger.Debug("Couldn't load {0}", fileVersionInfo.FileDescription);
                        throw new Win32Exception();
                    }
                }
                else if (comFallback)
                {
                    _logger.Debug("No lib, load from Global COM {0}", clsid);
                    Type type = Type.GetTypeFromCLSID(clsid);
                    return(Activator.CreateInstance(type));
                }
                else
                {
                    throw new Win32Exception();
                }
            }
            else if (comFallback)
            {
                _logger.Debug("Load from Global COM {0}", clsid);
                Type type = Type.GetTypeFromCLSID(clsid);
                return(Activator.CreateInstance(type));
            }

            _logger.Debug("Got Object {0} from {1}", createdObject, clsid);
            return(createdObject);
        }