Esempio n. 1
0
        public static object GetObjectForIUnknown(IntPtr ptr)
        {
            if (ptr == IntPtr.Zero)
            {
                return(null);
            }

            int startRef = 0, endRef = 0;

            // Mono bug : Marshal.GetObjectForIUnknown is decrementing the COM objects ref count not incrementing in.
            if (IsMono)
            {
                startRef = Marshal.AddRef(ptr);
            }

            object ret = Marshal.GetObjectForIUnknown(ptr);

            if (IsMono)
            {
                endRef = Marshal.AddRef(ptr);
                if (endRef > startRef + 1)
                {
                    Debug.WriteLine("mono GetObjectForIUknown bug has been fixed! Please delete this fix.");
                }
            }

            return(ret);
        }
Esempio n. 2
0
 public void GetStreamDescriptor(/*IMFStreamDescriptor*/ out IntPtr ppStreamDescriptor)
 {
     CheckShutdown();
     Trace.WriteLine($"RtspMediaStream<{Type}>::GetStreamDescriptor()");
     ppStreamDescriptor = Descriptor.NativePointer;
     Marshal.AddRef(Descriptor.NativePointer);
 }
Esempio n. 3
0
        public int FindAndLockDocument(uint dwRDTLockType, string pszMkDocument, out IVsHierarchy ppHier, out uint pitemid, out IntPtr ppunkDocData, out uint pdwCookie)
        {
            uint id;

            if (_ids.TryGetValue(pszMkDocument, out id))
            {
                var docInfo  = _table[id];
                var lockType = (_VSRDTFLAGS)dwRDTLockType;

                ppHier  = docInfo.Hierarchy;
                pitemid = docInfo.ItemId;
                if (docInfo.DocData != IntPtr.Zero)
                {
                    Marshal.AddRef(docInfo.DocData);
                }
                ppunkDocData  = docInfo.DocData;
                pdwCookie     = id;
                docInfo.Flags = (_VSRDTFLAGS)dwRDTLockType;
                if (lockType.HasFlag(_VSRDTFLAGS.RDT_ReadLock) || lockType.HasFlag(_VSRDTFLAGS.RDT_EditLock))
                {
                    docInfo.LockCount++;
                }
                return(VSConstants.S_OK);
            }
            ppHier       = null;
            pitemid      = 0;
            ppunkDocData = IntPtr.Zero;
            pdwCookie    = 0;
            return(VSConstants.S_FALSE);
        }
Esempio n. 4
0
        /// <summary>
        /// Meldet, dass nun eine Verbindung zu einem anderen Endpunkt festgelegt wurde.
        /// </summary>
        /// <param name="connector">Ein anderer Endpunkt.</param>
        /// <param name="mediaType">Die Art der Daten, die zwischen den Endpunkten ausgetauscht werden.</param>
        public void ReceiveConnection(IntPtr connector, IntPtr mediaType)
        {
            // Free
            Disconnect();

            // Remember
            if (connector != null)
            {
                Marshal.AddRef(connector);
            }
            m_Connected = connector;

            // Clone the media type
            m_ConnectType.Dispose();
            m_ConnectType = new MediaType(mediaType);

            // Attach to raw COM interface
            m_MemPin = ComIdentity.QueryInterface(m_Connected, typeof(IMemInputPin));

            // Get the delegate for the calls - dirty but we have to avoid automatic marshalling inside the graph
            IntPtr comFunctionTable = Marshal.ReadIntPtr(m_MemPin);
            IntPtr receiveSingle    = Marshal.ReadIntPtr(comFunctionTable, 24);
            IntPtr notifyAllocator  = Marshal.ReadIntPtr(comFunctionTable, 16);

            m_MemSink    = (MediaSampleSink)Marshal.GetDelegateForFunctionPointer(receiveSingle, typeof(MediaSampleSink));
            m_NotifySink = (NotifyAllocatorSink)Marshal.GetDelegateForFunctionPointer(notifyAllocator, typeof(NotifyAllocatorSink));
        }
Esempio n. 5
0
        /// <summary>
        /// The GetSurface method retrieves a Direct3D surface
        /// </summary>
        /// <param name="userId">
        /// Application-defined identifier. This value is
        /// the same value that the application passed to the
        /// IVMRSurfaceAllocatorNotify9.AdviseSurfaceAllocator
        /// method in the dwUserID parameter.
        /// </param>
        /// <param name="surfaceIndex">
        /// Specifies the index of the surface to retrieve.
        /// </param>
        /// <param name="surfaceFlags"></param>
        /// <param name="lplpSurface">
        /// Address of a variable that receives an IDirect3DSurface9
        /// interface pointer. The caller must release the interface.</param>
        /// <returns></returns>
        public int GetSurface(IntPtr userId, int surfaceIndex, int surfaceFlags, out IntPtr lplpSurface)
        {
            lplpSurface = IntPtr.Zero;

            if (DxSurfaces == null)
            {
                return(E_FAIL);
            }

            if (surfaceIndex > DxSurfaces.Length)
            {
                return(E_FAIL);
            }

            lock (m_instanceLock)
            {
                if (DxSurfaces == null)
                {
                    return(E_FAIL);
                }

                lplpSurface = DxSurfaces[surfaceIndex];

                /* Increment the reference count to our surface,
                 * which is a pointer to a COM object */
                Marshal.AddRef(lplpSurface);
                return(0);
            }
        }
Esempio n. 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="grfCreateDoc"></param>
        /// <param name="pszMkDocument"></param>
        /// <param name="pszPhysicalView"></param>
        /// <param name="pvHier"></param>
        /// <param name="itemid"></param>
        /// <param name="punkDocDataExisting"></param>
        /// <param name="ppunkDocView"></param>
        /// <param name="ppunkDocData"></param>
        /// <param name="pbstrEditorCaption"></param>
        /// <param name="pguidCmdUI"></param>
        /// <param name="pgrfCDW"></param>
        /// <returns></returns>
        public virtual int CreateEditorInstance(
            uint createEditorFlags,
            string documentMoniker,
            string physicalView,
            IVsHierarchy hierarchy,
            uint itemid,
            System.IntPtr docDataExisting,
            out System.IntPtr docView,
            out System.IntPtr docData,
            out string editorCaption,
            out Guid commandUIGuid,
            out int createDocumentWindowFlags)
        {
            // Initialize output parameters
            docView                   = IntPtr.Zero;
            docData                   = IntPtr.Zero;
            commandUIGuid             = Guid.Empty;
            createDocumentWindowFlags = 0;
            editorCaption             = null;

            // Validate inputs
            if ((createEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            if (_promptEncodingOnLoad && docDataExisting != IntPtr.Zero)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            // Get a text buffer
            IVsTextLines textLines = GetTextBuffer(docDataExisting);

            // Assign docData IntPtr to either existing docData or the new text buffer
            if (docDataExisting != IntPtr.Zero)
            {
                docData = docDataExisting;
                Marshal.AddRef(docData);
            }
            else
            {
                docData = Marshal.GetIUnknownForObject(textLines);
            }

            try {
                docView = CreateDocumentView(documentMoniker, physicalView, hierarchy, itemid, textLines, out editorCaption, out commandUIGuid);
            } finally {
                if (docView == IntPtr.Zero)
                {
                    if (docDataExisting != docData && docData != IntPtr.Zero)
                    {
                        // Cleanup the instance of the docData that we have addref'ed
                        Marshal.Release(docData);
                        docData = IntPtr.Zero;
                    }
                }
            }
            return(VSConstants.S_OK);
        }
        public void UpdateSurface(D3DImage previewSurface, string bsChannelID, string bsEventName, string bsEventParam, object pEventObject)
        {
            if (bsEventName == "wpf_nextframe")
            {
                IntPtr pSurfaceIUnk = Marshal.GetIUnknownForObject(pEventObject);
                if (pSurfaceIUnk != SavedSurfaceIUnk)
                {
                    if (SavedSurfaceIUnk != IntPtr.Zero)
                    {
                        Marshal.Release(SavedSurfaceIUnk);
                    }

                    SavedSurfaceIUnk = pSurfaceIUnk;
                    Marshal.AddRef(SavedSurfaceIUnk);

                    previewSurface.Lock();
                    previewSurface.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                    previewSurface.SetBackBuffer(D3DResourceType.IDirect3DSurface9, SavedSurfaceIUnk);
                    previewSurface.Unlock();
                }

                if (pSurfaceIUnk != IntPtr.Zero)
                {
                    Marshal.Release(pSurfaceIUnk);
                }

                previewSurface.Lock();
                previewSurface.AddDirtyRect(new Int32Rect(0, 0, previewSurface.PixelWidth, previewSurface.PixelHeight));
                previewSurface.Unlock();
            }

            Marshal.ReleaseComObject(pEventObject);
        }
Esempio n. 8
0
        public void IsOperatorRefCounterTest()
        {
            // operator is is increment com ref count - but RCW cleanup free's both references.
            // (This is a change from .net 3.5 -> 4.0)
            var item1 = Xpcom.CreateInstance <nsISupports>(Contracts.Array);
            var ptr   = Marshal.GetIUnknownForObject(item1);

            Marshal.Release(ptr);

            int comCount1 = ComDebug.GetComRefCount(item1);
            int rcwCount1 = ComDebug.GetRcwRefCount(item1);

            bool test = item1 is nsIArray;

            int comCount2 = ComDebug.GetComRefCount(item1);
            int rcwCount2 = ComDebug.GetRcwRefCount(item1);

            Marshal.AddRef(ptr);
            int free = Marshal.ReleaseComObject(item1);

            Assert.AreEqual(0, Marshal.Release(ptr), "Releasing the RCW by ReleaseComObject should have called Release twice.");

            Assert.AreEqual(1, comCount2 - comCount1);
            Assert.AreEqual(0, rcwCount2 - rcwCount1);
            Assert.AreEqual(0, free);
        }
        public virtual int AddRef()
        {
            IntPtr pUnk = Marshal.GetIUnknownForObject(this);

            Marshal.AddRef(pUnk);
            return(Marshal.Release(pUnk));
        }
Esempio n. 10
0
        public int RegisterAndLockDocument(uint grfRDTLockType, string pszMkDocument, IVsHierarchy pHier, uint itemid, IntPtr punkDocData, out uint pdwCookie)
        {
            uint cookie = 0;
            int  res    = _vs.Invoke(() => {
                cookie         = _ids[pszMkDocument] = ++_curCookie;
                _table[cookie] = new DocInfo(
                    (_VSRDTFLAGS)grfRDTLockType,
                    pszMkDocument,
                    pHier,
                    itemid,
                    punkDocData,
                    cookie
                    );

                if (punkDocData != IntPtr.Zero)
                {
                    Marshal.AddRef(punkDocData);
                }
                var persist = (IVsPersistDocData)Marshal.GetObjectForIUnknown(punkDocData);
                return(persist.OnRegisterDocData(cookie, pHier, itemid));
            });

            pdwCookie = cookie;
            return(res);
        }
Esempio n. 11
0
        public void QueryInterfaceRefCounterTest()
        {
            var item1 = Xpcom.CreateInstance <nsISupports>(Contracts.Array);
            var ptr   = Marshal.GetIUnknownForObject(item1);

            Marshal.Release(ptr);

            int comCount1 = ComDebug.GetComRefCount(item1);
            int rcwCount1 = ComDebug.GetRcwRefCount(item1);

            var item2 = Xpcom.QueryInterface <nsIArray>(item1);

            int comCount2 = ComDebug.GetComRefCount(item2);
            int rcwCount2 = ComDebug.GetRcwRefCount(item2);

            Marshal.AddRef(ptr);
            int free1 = Marshal.ReleaseComObject(item2);
            int free2 = Marshal.ReleaseComObject(item1);

            Assert.AreEqual(0, Marshal.Release(ptr));


            Assert.AreEqual(1, comCount2 - comCount1);
            Assert.AreEqual(1, rcwCount2 - rcwCount1);
            Assert.AreEqual(1, free1);
            Assert.AreEqual(0, free2);
        }
 public DropTargetPassthrough(IntPtr passthrough, ExtendedListViewCommon parent)
 {
     this.passthrough = passthrough;
     Marshal.AddRef(passthrough);
     this.parent = parent;
     Pointer     = Marshal.GetComInterfaceForObject(this, typeof(_IDropTarget));
 }
        public void SetStatus(
            int flags,
            int hResult,
            String message,
            IntPtr pErrObj)
        {
            IWbemClassObjectFreeThreaded errObj = null;

            if (pErrObj != IntPtr.Zero)
            {
                Marshal.AddRef(pErrObj);
                errObj = new IWbemClassObjectFreeThreaded(pErrObj);
            }
            // TODO: errObj never used

            try {
                if (null != eventWatcher)
                {
                    // Fire Stopped event
                    eventWatcher.FireStopped(new StoppedEventArgs(context, hResult));

                    // Unhook the parent watcher
                    eventWatcher = null;
                }

                ReleaseStub();
            } catch {}
        }
        public void SetStatus(
            int flags,
            int hResult,
            String message,
            IntPtr pErrObj)
        {
#if TODO_ERROBJ_NEVER_USED
            IWbemClassObjectFreeThreaded errObj = null;
            if (pErrObj != IntPtr.Zero)
            {
                Marshal.AddRef(pErrObj);
                errObj = new IWbemClassObjectFreeThreaded(pErrObj);
            }
#endif // TODO_ERROBJ_NEVER_USED

            try
            {
                // Fire Stopped event
                eventWatcher.FireStopped(new StoppedEventArgs(context, hResult));

                //This handles cases in which WMI calls SetStatus to indicate a problem, for example
                //a queue overflow due to slow client processing.
                //Currently we just cancel the subscription in this case.
                // BUG# 97657 - When you cancel a call with CancelAsyncCall, on Windows 2000,
                // you get a SetStatus with WBEM_E_CALL_CANCELLED.  On Windows XP, you get
                // a set status with WBEM_S_OPERATION_CANCELLED!!!
                if (hResult != (int)tag_WBEMSTATUS.WBEM_E_CALL_CANCELLED &&
                    hResult != (int)tag_WBEMSTATUS.WBEM_S_OPERATION_CANCELLED)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Cancel2));                    // Cancel(); // BUG#118550 - On Win2k, we get a deadlock if we do a Cancel within a SetStatus
                }
            }
            catch {}
        }
Esempio n. 15
0
        private void SetManagedDevice(IntPtr unmanagedDevice)
        {
            // Start by freeing everything
            FreeResources();

            // Create a managed Device from the unmanaged pointer
            // The constructor don't call IUnknown.AddRef but the "destructor" seem to call IUnknown.Release
            // Direct3D seem to be happier with that according to the DirectX log
            Marshal.AddRef(unmanagedDevice);
            this.unmanagedDevice = unmanagedDevice;
            device = new Device(unmanagedDevice);

            // Create helper objects to draw over the video
            sprite  = new Sprite(device);
            gdiFont = new System.Drawing.Font("Tahoma", 15);
            d3dFont = new Direct3D.Font(device, gdiFont);

            // Load a bitmap (the spider) from embedded resources. This is a png file with alpha transparency
            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DirectShowLib.Sample.redspider.png"))
            {
                spiderTex = TextureLoader.FromStream(device, stream, D3DX.Default, D3DX.Default, D3DX.Default, D3DX.Default, Usage.None, Format.A8R8G8B8, Pool.Default, Filter.None, Filter.None, 0);
                SurfaceDescription spiderDesc = spiderTex.GetLevelDescription(0);
                spiderSize = new Size(spiderDesc.Width, spiderDesc.Height);
            }
        }
        /// <summary>
        /// The method is call every 5 seconds to GC the managed heap after
        /// the COM server is started.
        /// </summary>
        /// <param name="stateInfo"></param>
        private static void GarbageCollect(object stateInfo)
        {
            ClassFactory lObject = (ClassFactory)stateInfo;

            if (lObject == null)
            {
                return;
            }

            if (lObject != null && lObject.mIntPtrObject != null && lObject.mIntPtrObject != IntPtr.Zero)
            {
                var k = Marshal.AddRef(lObject.mIntPtrObject);

                if (k <= 2)
                {
                    if (System.Windows.Application.Current != null)
                    {
                        System.Windows.Application.Current.Dispatcher.Invoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(() =>
                        {
                            System.Windows.Application.Current.Shutdown();
                        }));
                    }
                    else
                    {
                        System.Diagnostics.Process.GetCurrentProcess().Kill();
                    }
                }

                Marshal.Release(lObject.mIntPtrObject);
            }

            GC.Collect();   // GC
        }
Esempio n. 17
0
        /// <summary>
        /// Nimmt ein einzelnes Datenpaket entgegen.
        /// </summary>
        /// <param name="rawSample">Die COM Schnittstelle des Paketes.</param>
        public void Receive(IntPtr rawSample)
        {
            // Increment reference counter - will be released by wrapper
            Marshal.AddRef(rawSample);

            // Wrap it
            using (var sample = new NoMarshalComObjects.MediaSample(rawSample))
                try
                {
                    // Skip
                    if (!m_Running)
                    {
                        return;
                    }

                    // No parser
                    if (m_Parser == null)
                    {
                        return;
                    }

                    // Attach to the information
                    int size = sample.ActualDataLength;

                    // Skip
                    if (size < 1)
                    {
                        return;
                    }

                    // Attach to data
                    var data   = sample.BaseAddress;
                    var buffer = new byte[size];

                    // Fill
                    Marshal.Copy(data, buffer, 0, buffer.Length);

                    // Process
                    m_Parser.AddPayload(buffer);

                    // Synchronize
                    if (m_Dump != null)
                    {
                        lock (m_DumpLock)
                            if (m_Dump != null)
                            {
                                m_Dump.Write(buffer, 0, buffer.Length);
                            }
                    }
                }
                finally
                {
                    // Forward
                    if (m_TIF != null)
                    {
                        m_TIF.Receive(rawSample);
                    }
                }
        }
Esempio n. 18
0
        private void InitializeWebKit()
        {
            activationContext.Activate();

            frameLoadDelegate = new WebFrameLoadDelegate();
            Marshal.AddRef(Marshal.GetIUnknownForObject(frameLoadDelegate));

            downloadDelegate = new WebDownloadDelegate();
            Marshal.AddRef(Marshal.GetIUnknownForObject(downloadDelegate));

            policyDelegate = new WebPolicyDelegate(AllowNavigation, AllowDownloads, AllowNewWindows);
            Marshal.AddRef(Marshal.GetIUnknownForObject(policyDelegate));

            uiDelegate = new WebUIDelegate(this);
            Marshal.AddRef(Marshal.GetIUnknownForObject(uiDelegate));

            webView.setPolicyDelegate(policyDelegate);
            webView.setFrameLoadDelegate(frameLoadDelegate);
            webView.setDownloadDelegate(downloadDelegate);
            webView.setUIDelegate(uiDelegate);

            webView.setHostWindow(this.host.Handle.ToInt32());

            tagRECT rect = new tagRECT();

            rect.top    = rect.left = 0;
            rect.bottom = this.host.Height - 1;
            rect.right  = this.host.Width - 1;
            webView.initWithFrame(rect, null, null);

            IWebViewPrivate webViewPrivate = (IWebViewPrivate)webView;

            webViewHWND = (IntPtr)webViewPrivate.viewWindow();

            // Subscribe to FrameLoadDelegate events
            frameLoadDelegate.DidRecieveTitle                 += new DidRecieveTitleEvent(frameLoadDelegate_DidRecieveTitle);
            frameLoadDelegate.DidFinishLoadForFrame           += new DidFinishLoadForFrameEvent(frameLoadDelegate_DidFinishLoadForFrame);
            frameLoadDelegate.DidStartProvisionalLoadForFrame += new DidStartProvisionalLoadForFrameEvent(frameLoadDelegate_DidStartProvisionalLoadForFrame);
            frameLoadDelegate.DidCommitLoadForFrame           += new DidCommitLoadForFrameEvent(frameLoadDelegate_DidCommitLoadForFrame);
            frameLoadDelegate.DidFailLoadWithError            += new DidFailLoadWithErrorEvent(frameLoadDelegate_DidFailLoadWithError);
            frameLoadDelegate.DidFailProvisionalLoadWithError += new DidFailProvisionalLoadWithErrorEvent(frameLoadDelegate_DidFailProvisionalLoadWithError);
            frameLoadDelegate.DidClearWindowObject            += new DidClearWindowObjectEvent(frameLoadDelegate_DidClearWindowObject);

            // DownloadDelegate events
            downloadDelegate.DidReceiveResponse     += new DidReceiveResponseEvent(downloadDelegate_DidReceiveResponse);
            downloadDelegate.DidReceiveDataOfLength += new DidReceiveDataOfLengthEvent(downloadDelegate_DidReceiveDataOfLength);
            downloadDelegate.DecideDestinationWithSuggestedFilename += new DecideDestinationWithSuggestedFilenameEvent(downloadDelegate_DecideDestinationWithSuggestedFilename);
            downloadDelegate.DidBegin         += new DidBeginEvent(downloadDelegate_DidBegin);
            downloadDelegate.DidFinish        += new DidFinishEvent(downloadDelegate_DidFinish);
            downloadDelegate.DidFailWithError += new DidFailWithErrorEvent(downloadDelegate_DidFailWithError);

            // UIDelegate events
            uiDelegate.CreateWebViewWithRequest              += new CreateWebViewWithRequestEvent(uiDelegate_CreateWebViewWithRequest);
            uiDelegate.RunJavaScriptAlertPanelWithMessage    += new RunJavaScriptAlertPanelWithMessageEvent(uiDelegate_RunJavaScriptAlertPanelWithMessage);
            uiDelegate.RunJavaScriptConfirmPanelWithMessage  += new RunJavaScriptConfirmPanelWithMessageEvent(uiDelegate_RunJavaScriptConfirmPanelWithMessage);
            uiDelegate.RunJavaScriptTextInputPanelWithPrompt += new RunJavaScriptTextInputPanelWithPromptEvent(uiDelegate_RunJavaScriptTextInputPanelWithPrompt);

            activationContext.Deactivate();
        }
Esempio n. 19
0
        public int Advise(ICredentialProviderCredentialEvents pcpce)
        {
            events = pcpce;
            var intPtr = Marshal.GetIUnknownForObject(pcpce);

            Marshal.AddRef(intPtr);
            return(HResultValues.S_OK);
        }
 void IAppDomainHelper.Initialize(IntPtr pUnkAD, IntPtr pfnShutdownCB, IntPtr punkPool)
 {
     this._ad            = (AppDomain)Marshal.GetObjectForIUnknown(pUnkAD);
     this._pfnShutdownCB = pfnShutdownCB;
     this._punkPool      = punkPool;
     Marshal.AddRef(this._punkPool);
     this._ad.DomainUnload += new EventHandler(this.OnDomainUnload);
 }
Esempio n. 21
0
        public SafeIUnknownRef CreateRef()
        {
            Marshal.AddRef(base.handle);
            SafeIUnknownRef ref1 = new SafeIUnknownRef();

            ref1.SetHandle(base.handle);
            return(ref1);
        }
Esempio n. 22
0
File: ABI.cs Progetto: ETLang/Gluon
 public static IntPtr ToABI_Object(IntPtr x)
 {
     if (x != IntPtr.Zero)
     {
         Marshal.AddRef(x);
     }
     return(x);
 }
Esempio n. 23
0
 public static IntPtr AddRef(this IntPtr comObj)
 {
     if (comObj != IntPtr.Zero)
     {
         Marshal.AddRef(comObj);
     }
     return(comObj);
 }
Esempio n. 24
0
        public static SafeIUnknownRef AddRef(IntPtr pObject)
        {
            Marshal.AddRef(pObject);
            SafeIUnknownRef ref1 = new SafeIUnknownRef();

            ref1.SetHandle(pObject);
            return(ref1);
        }