コード例 #1
0
            /// <summary>
            /// This method validates that the given weak reference is alive.
            /// 1. IWeakReference->Resolve method returns the target's interface for the mapping IID passed to it.
            /// 2. If the object is not alive it returns null.
            /// 2. From the returned interface we get or create a new RCW and return it.
            /// </summary>
            /// <returns></returns>
            internal unsafe object Resolve()
            {
                IntPtr pInspectable;
                __com_IWeakReference *pComIWeakReference = (__com_IWeakReference *)m_pComWeakRef;
                Guid inspectableIID = Interop.COM.IID_IInspectable;
                int  result         = CalliIntrinsics.StdCall__int(
                    pComIWeakReference->pVtable->pfnResolve,
                    m_pComWeakRef,
                    &inspectableIID,
                    &pInspectable);

                if (result >= 0 && pInspectable != IntPtr.Zero)
                {
                    try
                    {
                        return(McgMarshal.ComInterfaceToObject(pInspectable, McgModuleManager.IInspectable));
                    }
                    finally
                    {
                        // Release the pInspectable.
                        McgMarshal.ComRelease(pInspectable);
                    }
                }

                return(null);
            }
コード例 #2
0
ファイル: McgComHelpers.cs プロジェクト: tedd/corert
        static object ComInterfaceToObjectInternal_NoManagedUnboxing(
            IntPtr pComItf,
            RuntimeTypeHandle interfaceType,
            RuntimeTypeHandle classTypeInSignature,
            CreateComObjectFlags flags)
        {
            if (pComItf == default(IntPtr))
            {
                return(null);
            }

            //
            // Is this a CCW?
            //
            ComCallableObject ccw;

            if (ComCallableObject.TryGetCCW(pComItf, out ccw))
            {
                return(ccw.TargetObject);
            }

            //
            // This pointer is not a CCW, but we need to do one additional check here for aggregation
            // In case the COM pointer is a interface implementation from native, but the outer object is a
            // managed object
            //
            IntPtr pComIdentityIUnknown = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IUnknown);

            if (pComIdentityIUnknown == default(IntPtr))
            {
                throw new InvalidCastException();
            }

            try
            {
                //
                // Check whether the identity COM pointer to see if it is a aggregating CCW
                //
                if (ComCallableObject.TryGetCCW(pComIdentityIUnknown, out ccw))
                {
                    return(ccw.TargetObject);
                }

                //
                // Nope, not a CCW - let's go down our RCW creation code path
                //
                return(ComInterfaceToComObjectInternal(
                           pComItf,
                           pComIdentityIUnknown,
                           interfaceType,
                           classTypeInSignature,
                           ContextCookie.Default,
                           flags
                           ));
            }
            finally
            {
                McgMarshal.ComRelease(pComIdentityIUnknown);
            }
        }
コード例 #3
0
ファイル: McgComHelpers.cs プロジェクト: tedd/corert
        /// <summary>
        /// Returns runtime class name for a specific object
        /// </summary>
        internal static string GetRuntimeClassName(Object obj)
        {
#if  ENABLE_MIN_WINRT
            System.IntPtr pWinRTItf = default(IntPtr);

            try
            {
                pWinRTItf = McgMarshal.ObjectToIInspectable(obj);
                if (pWinRTItf == default(IntPtr))
                {
                    return(String.Empty);
                }
                else
                {
                    return(GetRuntimeClassName(pWinRTItf));
                }
            }
            finally
            {
                if (pWinRTItf != default(IntPtr))
                {
                    McgMarshal.ComRelease(pWinRTItf);
                }
            }
#else
            return(string.Empty);
#endif
        }
コード例 #4
0
ファイル: McgComHelpers.cs プロジェクト: noahfalk/corert
        /// <summary>
        /// Returns runtime class name for a specific object
        /// </summary>
        internal static string GetRuntimeClassName(Object obj)
        {
#if  ENABLE_WINRT
            System.IntPtr pWinRTItf = default(IntPtr);

            try
            {
                pWinRTItf = McgMarshal.ObjectToIInspectable(obj);
                if (pWinRTItf == default(IntPtr))
                {
                    return(String.Empty);
                }
                else
                {
                    return(GetRuntimeClassName(pWinRTItf));
                }
            }
            finally
            {
                if (pWinRTItf != default(IntPtr))
                {
                    McgMarshal.ComRelease(pWinRTItf);
                }
            }
#else
            throw new PlatformNotSupportedException("GetRuntimeClassName");
#endif
        }
コード例 #5
0
ファイル: McgComHelpers.cs プロジェクト: noahfalk/corert
        /// <summary>
        /// Release a IStream that has marshalled data in it
        /// </summary>
        internal static void SafeReleaseStream(IntPtr pStream)
        {
            Debug.Assert(pStream != default(IntPtr));
#if ENABLE_WINRT
            // Release marshalled data and ignore any error
            ExternalInterop.CoReleaseMarshalData(pStream);

            McgMarshal.ComRelease(pStream);
#else
            throw new PlatformNotSupportedException("SafeReleaseStream");
#endif
        }
コード例 #6
0
#pragma warning restore 649, 169

        /// <summary>
        /// This method gets called every time the WeakReference or WeakReference'1 set the Target.
        /// We can have 4 possible combination here.
        /// a. Target is a GC object and it is either getting set for the first time or previous object is also GC object.
        ///     In this case we do not need to do anything.
        ///
        /// b. Target is a GC object and previous target was __ComObject
        ///    i. We remove the element from ConditionalWeakTable.
        ///   ii. When the GC collects this ComWeakReference the finalizer will ensure that the native object is released.
        ///
        /// c. Target is a __ComObject and the previous target was null or GC object.
        ///    We simply add the new target to the dictionary.
        ///
        /// d. Target is a __COmObject and the previous object was __COmObject.
        ///    i. We first remove the element from the ConditionalWeakTable.
        ///   ii. When the GC collects the previous ComWeakReference the finalizer will ensure that the native object is released.
        ///  iii. We add the new ComWeakReference to the conditionalWeakTable.
        /// </summary>
        /// <param name="weakReference"></param>
        /// <param name="target"></param>
        public static unsafe void SetTarget(object weakReference, object target)
        {
            Contract.Assert(weakReference != null);

            // Check if this weakReference is already associated with a native target.
            ComWeakReference pOldComWeakReference;

            if (s_COMWeakReferenceTable.TryGetValue(weakReference, out pOldComWeakReference))
            {
                // Remove the previous target.
                // We do not have to release the native ComWeakReference since it will be done as part of the finalizer.
                s_COMWeakReferenceTable.Remove(weakReference);
            }

            // Now check whether the current target is __ComObject.
            // However, we don't want to pass the QI to a managed object deriving from native object - we
            // would end up passing the QI to back the CCW and end up stack overflow
            __ComObject comObject = target as __ComObject;

            if (comObject != null && !comObject.ExtendsComObject)
            {
                // Get the IWeakReferenceSource for the given object
                IntPtr pWeakRefSource = McgMarshal.ObjectToComInterface(comObject, McgModuleManager.IWeakReferenceSource);

                if (pWeakRefSource != IntPtr.Zero)
                {
                    IntPtr pWeakRef = IntPtr.Zero;
                    try
                    {
                        // Now that we have the IWeakReferenceSource , we need to call the GetWeakReference method to get the corresponding IWeakReference
                        __com_IWeakReferenceSource *pComWeakRefSource = (__com_IWeakReferenceSource *)pWeakRefSource;
                        int result = CalliIntrinsics.StdCall <int>(
                            pComWeakRefSource->pVtable->pfnGetWeakReference,
                            pWeakRefSource,
                            out pWeakRef);
                        if (result >= 0 && pWeakRef != IntPtr.Zero)
                        {
                            // Since we have already checked s_COMWeakReferenceTable for the weak reference, we can simply add the entry w/o checking.
                            // PS - We do not release the pWeakRef as it should be alive until the ComWeakReference is alive.
                            s_COMWeakReferenceTable.Add(weakReference, new ComWeakReference(ref pWeakRef));
                        }
                    }
                    finally
                    {
                        McgMarshal.ComSafeRelease(pWeakRef);
                        McgMarshal.ComRelease(pWeakRefSource);
                    }
                }
            }
        }
コード例 #7
0
ファイル: McgComHelpers.cs プロジェクト: tedd/corert
        /// <summary>
        /// Returns the existing RCW or create a new RCW from the COM interface pointer
        /// NOTE: Don't use this overload if you already have the identity IUnknown
        /// </summary>
        /// <param name="expectedContext">
        /// The current context of this thread. If it is passed and is not Default, we'll check whether the
        /// returned RCW from cache matches this expected context. If it is not a match (from a different
        /// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new
        /// RCW instead - which will always end up in the current context
        /// We'll skip the check if current == ContextCookie.Default.
        /// </param>
        internal static object ComInterfaceToComObject(
            IntPtr pComItf,
            RuntimeTypeHandle interfaceType,
            RuntimeTypeHandle classTypeInSigature,
            ContextCookie expectedContext,
            CreateComObjectFlags flags
            )
        {
            Debug.Assert(expectedContext.IsDefault || expectedContext.IsCurrent);

            //
            // Get identity IUnknown for lookup
            //
            IntPtr pComIdentityIUnknown = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IUnknown);

            if (pComIdentityIUnknown == default(IntPtr))
            {
                throw new InvalidCastException();
            }

            try
            {
                object obj = ComInterfaceToComObjectInternal(
                    pComItf,
                    pComIdentityIUnknown,
                    interfaceType,
                    classTypeInSigature,
                    expectedContext,
                    flags
                    );

                return(obj);
            }
            finally
            {
                McgMarshal.ComRelease(pComIdentityIUnknown);
            }
        }
コード例 #8
0
ファイル: MarshalImpl.cs プロジェクト: wffy/corert
 public static int Release(IntPtr pUnk)
 {
     return(McgMarshal.ComRelease(pUnk));
 }
コード例 #9
0
ファイル: McgComHelpers.cs プロジェクト: tedd/corert
        /// <summary>
        /// Returns the existing RCW or create a new RCW from the COM interface pointer
        /// NOTE: This does not do any unboxing at all.
        /// </summary>
        /// <param name="expectedContext">
        /// The current context of this thread. If it is passed and is not Default, we'll check whether the
        /// returned RCW from cache matches this expected context. If it is not a match (from a different
        /// context, and is not free threaded), we'll go ahead ignoring the cached entry, and create a new
        /// RCW instead - which will always end up in the current context
        /// We'll skip the check if current == ContextCookie.Default.
        /// </param>
        private static object ComInterfaceToComObjectInternal_NoCache(
            IntPtr pComItf,
            IntPtr pComIdentityIUnknown,
            RuntimeTypeHandle interfaceType,
            RuntimeTypeHandle classTypeInSignature,
            ContextCookie expectedContext,
            CreateComObjectFlags flags,
            out string className
            )
        {
            className = null;

            //
            // Lookup RCW in global RCW cache based on the identity IUnknown
            //
            __ComObject comObject = ComObjectCache.Lookup(pComIdentityIUnknown);

            if (comObject != null)
            {
                bool useThisComObject = true;

                if (!expectedContext.IsDefault)
                {
                    //
                    // Make sure the returned RCW matches the context we specify (if any)
                    //
                    if (!comObject.IsFreeThreaded &&
                        !comObject.ContextCookie.Equals(expectedContext))
                    {
                        //
                        // This is a mismatch.
                        // We only care about context for WinRT factory RCWs (which is the only place we are
                        // passing in the context right now).
                        // When we get back a WinRT factory RCW created in a different context. This means the
                        // factory is a singleton, and the returned IActivationFactory could be either one of
                        // the following:
                        // 1) A raw pointer, and it acts like a free threaded object
                        // 2) A proxy that is used across different contexts. It might maintain a list of contexts
                        // that it is marshaled to, and will fail to be called if it is not marshaled to this
                        // context yet.
                        //
                        // In this case, it is unsafe to use this RCW in this context and we should proceed
                        // to create a duplicated one instead. It might make sense to have a context-sensitive
                        // RCW cache but I don't think this case will be common enough to justify it
                        //
                        // @TODO: Check for DCOM proxy as well
                        useThisComObject = false;
                    }
                }

                if (useThisComObject)
                {
                    //
                    // We found one - AddRef and return
                    //
                    comObject.AddRef();
                    return(comObject);
                }
            }

            string winrtClassName = null;

            bool isSealed = false;

            if (!classTypeInSignature.IsNull())
            {
                isSealed = classTypeInSignature.IsSealed();
            }

            //
            // Only look at runtime class name if the class type in signature is not sealed
            // NOTE: In the case of System.Uri, we are not pass the class type, only the interface
            //
            if (!isSealed &&
                (flags & CreateComObjectFlags.SkipTypeResolutionAndUnboxing) == 0)
            {
                IntPtr pInspectable;

                bool needRelease = false;

                if (interfaceType.IsSupportIInspectable())
                {
                    //
                    // Use the interface pointer as IInspectable as we know it is indeed a WinRT interface that
                    // derives from IInspectable
                    //
                    pInspectable = pComItf;
                }
                else if ((flags & CreateComObjectFlags.IsWinRTObject) != 0)
                {
                    //
                    // Otherwise, if someone tells us that this is a WinRT object, but we don't have a
                    // IInspectable interface at hand, we'll QI for it
                    //
                    pInspectable = McgMarshal.ComQueryInterfaceNoThrow(pComItf, ref Interop.COM.IID_IInspectable);
                    needRelease  = true;
                }
                else
                {
                    pInspectable = default(IntPtr);
                }

                try
                {
                    if (pInspectable != default(IntPtr))
                    {
                        className      = McgComHelpers.GetRuntimeClassName(pInspectable);
                        winrtClassName = className;
                    }
                }
                finally
                {
                    if (needRelease && pInspectable != default(IntPtr))
                    {
                        McgMarshal.ComRelease(pInspectable);
                        pInspectable = default(IntPtr);
                    }
                }
            }

            //
            // 1. Prefer using the class returned from GetRuntimeClassName
            // 2. Otherwise use the class (if there) in the signature
            // 3. Out of options - create __ComObject
            //
            RuntimeTypeHandle classTypeToCreateRCW  = default(RuntimeTypeHandle);
            RuntimeTypeHandle interfaceTypeFromName = default(RuntimeTypeHandle);

            if (!String.IsNullOrEmpty(className))
            {
                if (!McgModuleManager.TryGetClassTypeFromName(className, out classTypeToCreateRCW))
                {
                    //
                    // If we can't find the class name in our map, try interface as well
                    // Such as IVector<Int32>
                    // This apparently won't work if we haven't seen the interface type in MCG
                    //
                    McgModuleManager.TryGetInterfaceTypeFromName(className, out interfaceTypeFromName);
                }
            }

            if (classTypeToCreateRCW.IsNull())
            {
                classTypeToCreateRCW = classTypeInSignature;
            }

            // Use identity IUnknown to create the new RCW
            // @TODO: Transfer the ownership of ref count to the RCW
            if (classTypeToCreateRCW.IsNull())
            {
                //
                // Create a weakly typed RCW because we have no information about this particular RCW
                // @TODO - what if this RCW is not seen by MCG but actually exists in WinMD and therefore we
                // are missing GCPressure and ComMarshallingType information for this object?
                //
                comObject = new __ComObject(pComIdentityIUnknown, default(RuntimeTypeHandle));
            }
            else
            {
                //
                // Create a strongly typed RCW based on RuntimeTypeHandle
                //
                comObject = CreateComObjectInternal(classTypeToCreateRCW, pComIdentityIUnknown);            // Use identity IUnknown to create the new RCW
            }

#if DEBUG
            //
            // Remember the runtime class name for debugging purpose
            // This way you can tell what the class name is, even when we failed to create a strongly typed
            // RCW for it
            //
            comObject.m_runtimeClassName = className;
#endif

            //
            // Make sure we QI for that interface
            //
            if (!interfaceType.IsNull())
            {
                comObject.QueryInterface_NoAddRef_Internal(interfaceType, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false);
            }

            return(comObject);
        }