IntPtrs vs HandelRefs vs SafeHandles

Announcements and discussion for PInvoke

Moderators: Luke Jefferson, Robert

IntPtrs vs HandelRefs vs SafeHandles

Postby Pete R » Thu Oct 18, 2007 7:12 pm

Hi guys, I appreciate all the work done on this site, though things are still far from clear for me. It frankly boggles my mind that Microsoft doesn't thoroughly and officially document the correct P/Invoke signatures for the Win32 API, but so it goes. This appears to be the most definitive source(?) for the signatures, but I see some signature overloads using IntPtrs and others using HandleRefs and I'm not sure why there isn't consistency. And isn't it best to use SafeHandles if possible? For example the signature for OpenDesktop given here returns an IntPtr for the desktop handle. Wouldn't something like this be preferred:

Code: Select all
   
class SafeDesktopHandle : SafeHandle
    {
        private SafeDesktopHandle()
            : base(IntPtr.Zero, true)
        {
            return;
        }

        public override bool IsInvalid
        {
            get { return handle == IntPtr.Zero; }
        }

        [SuppressUnmanagedCodeSecurity]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool CloseDesktop(IntPtr handle);


        protected override bool ReleaseHandle()
        {
            return CloseDesktop(handle);
        }
    }



    [DllImport("user32.dll", SetLastError = true)]
    static extern SafeDesktopHandle OpenDesktop(string lpszDesktop, int dwFlags, bool fInherit, int dwDesiredAccess);


etc?

I use a lot of windows calls like EnumWindows and related, and I'm not sure whether to try to use HandleRefs, or create a SafeWindowHandle and try to figure when it should be used and when it shouldn't, etc, or use HandleRefs, or just toss GC.KeepAlives in every time I make an Interop call. Where can I find guidance on this? Thanks,

Pete
Pete R
 
Posts: 1
Joined: Thu Oct 18, 2007 6:54 pm

Return to PInvoke.Net

Who is online

Users browsing this forum: No registered users and 0 guests