当前位置: 首页>>代码示例>>C#>>正文


C# InteropServices.SafeHandle类代码示例

本文整理汇总了C#中System.Runtime.InteropServices.SafeHandle的典型用法代码示例。如果您正苦于以下问题:C# SafeHandle类的具体用法?C# SafeHandle怎么用?C# SafeHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SafeHandle类属于System.Runtime.InteropServices命名空间,在下文中一共展示了SafeHandle类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Write

		private static bool Write(SafeHandle fileHandle, string dumpType)
		{
			if (dumpType.ToLower() == MiniDumpType.Tiny.ToString().ToLower())
			{
				return Write(fileHandle, DumpTypeFlag.WithIndirectlyReferencedMemory | DumpTypeFlag.ScanMemory);
			}
			else if (dumpType.ToLower() == MiniDumpType.Normal.ToString().ToLower())
			{
				// If the debugger is attached, it is not possible to access private read-write memory
				if (Debugger.IsAttached)
				{
					return Write(fileHandle, DumpTypeFlag.WithDataSegs | DumpTypeFlag.WithHandleData | DumpTypeFlag.WithUnloadedModules);
				}
				else
				{
					// Bug: Combination of WithPrivateReadWriteMemory + WithDataSegs hangs Visual Studio 2010 SP1 on some cases while loading the minidump for debugging in mixed mode which was created in by a release build application
					return Write(fileHandle, DumpTypeFlag.WithPrivateReadWriteMemory | DumpTypeFlag.WithDataSegs | DumpTypeFlag.WithHandleData | DumpTypeFlag.WithUnloadedModules);
				}
			}
			else if (dumpType.ToLower() == MiniDumpType.Full.ToString().ToLower())
			{
				return Write(fileHandle, DumpTypeFlag.WithFullMemory);
			}
			else
			{
				throw NBugConfigurationException.Create(() => Settings.MiniDumpType, "Parameter supplied for settings property is invalid.");
			}
		}
开发者ID:dakahler,项目名称:alloclave,代码行数:28,代码来源:DumpWriter.cs

示例2: DisconnectEx

        internal bool DisconnectEx(SafeCloseSocket socketHandle, SafeHandle overlapped, int flags, int reserved)
        {
            EnsureDynamicWinsockMethods();
            DisconnectExDelegate disconnectEx = _dynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);

            return disconnectEx(socketHandle, overlapped, flags, reserved);
        }
开发者ID:Corillian,项目名称:corefx,代码行数:7,代码来源:Socket.Windows.cs

示例3: FPDF_LoadMemDocument

 public static IntPtr FPDF_LoadMemDocument(SafeHandle data_buf, int size, string password)
 {
     lock (LockString)
     {
         return Imports.FPDF_LoadMemDocument(data_buf, size, password);
     }
 }
开发者ID:tablesmit,项目名称:PdfiumViewer,代码行数:7,代码来源:NativeMethods.Pdfium.cs

示例4: CloseInvalidOutSafeHandle

 internal static void CloseInvalidOutSafeHandle(SafeHandle handle)
 {
     if (handle != null)
     {
         handle.SetHandleAsInvalid();
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:Utility.cs

示例5: SecurityPackageInfoClass

        /*
            This is to support SSL with no client cert.
            Important: safeHandle should not be Disposed during construction of this object.
           
            _SecPkgInfoW in sspi.h
         */
        internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Invalid handle: {safeHandle}");
                return;
            }

            IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);
            if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"unmanagedAddress: {unmanagedAddress}");

            // TODO (Issue #3114): replace with Marshal.PtrToStructure.
            Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Capabilities"));
            Version = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Version"));
            RPCID = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("RPCID"));
            MaxToken = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("MaxToken"));

            IntPtr unmanagedString;

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Name"));
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Name: {Name}");
            }

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Comment"));
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Comment: {Comment}");
            }

            if (NetEventSource.IsEnabled) NetEventSource.Info(this, this.ToString());
        }
开发者ID:dotnet,项目名称:corefx,代码行数:41,代码来源:SecurityPackageInfoClass.cs

示例6: Write

        public static bool Write(SafeHandle fileHandle, Option options, ExceptionInfo exceptionInfo = ExceptionInfo.None)
        {
            Process currentProcess = Process.GetCurrentProcess();
            IntPtr currentProcessHandle = currentProcess.Handle;
            var currentProcessId = (uint)currentProcess.Id;

            MiniDumpExceptionInformation exp;
            exp.ThreadId = GetCurrentThreadId();
            exp.ClientPointers = false;
            exp.ExceptionPointers = IntPtr.Zero;
            if (exceptionInfo == ExceptionInfo.Present)
            {
                exp.ExceptionPointers = Marshal.GetExceptionPointers();
            }

            var result = false;
            if (exp.ExceptionPointers == IntPtr.Zero)
            {
                result = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            }
            else
            {
                result = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, ref exp, IntPtr.Zero, IntPtr.Zero);
            }

            return result;
        }
开发者ID:gouranga,项目名称:CodeCounter,代码行数:27,代码来源:MiniDump.cs

示例7: AdjustTokenPrivileges

 internal static extern bool AdjustTokenPrivileges(SafeHandle TokenHandle,
     [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
     ref TOKEN_PRIVILEGES NewState,
     Int32 BufferLength,
     //ref TOKEN_PRIVILEGES PreviousState,					!! for some reason this won't accept null
     IntPtr PreviousState,
     IntPtr ReturnLength);
开发者ID:tke,项目名称:ManagedReparsePoints,代码行数:7,代码来源:Kernel32.cs

示例8: GetDescriptor

 public abstract bool GetDescriptor(SafeHandle interfaceHandle,
                                    byte descriptorType,
                                    byte index,
                                    ushort languageID,
                                    IntPtr buffer,
                                    int bufferLength,
                                    out int lengthTransferred);
开发者ID:arvydas,项目名称:BlinkStickDotNet,代码行数:7,代码来源:UsbApiBase.cs

示例9: SecurityPackageInfoClass

        /*
            This is to support SSL with no client cert.
            Important: safeHandle should not be Disposed during construction of this object.
           
            _SecPkgInfoW in sspi.h
         */
        internal SecurityPackageInfoClass(SafeHandle safeHandle, int index)
        {
            if (safeHandle.IsInvalid)
            {
                GlobalLog.Print("SecurityPackageInfoClass::.ctor() the pointer is invalid: " + (safeHandle.DangerousGetHandle()).ToString("x"));
                return;
            }

            IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index);
            GlobalLog.Print("SecurityPackageInfoClass::.ctor() unmanagedPointer: " + ((long)unmanagedAddress).ToString("x"));

            // TODO (Issue #3114): replace with Marshal.PtrToStructure.
            Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Capabilities"));
            Version = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Version"));
            RPCID = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("RPCID"));
            MaxToken = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("MaxToken"));

            IntPtr unmanagedString;

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Name"));
            if (unmanagedString != IntPtr.Zero)
            {
                Name = Marshal.PtrToStringUni(unmanagedString);
                GlobalLog.Print("Name: " + Name);
            }

            unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Comment"));
            if (unmanagedString != IntPtr.Zero)
            {
                Comment = Marshal.PtrToStringUni(unmanagedString);
                GlobalLog.Print("Comment: " + Comment);
            }

            GlobalLog.Print("SecurityPackageInfoClass::.ctor(): " + ToString());
        }
开发者ID:jemmy655,项目名称:corefx,代码行数:41,代码来源:SecurityPackageInfoClass.cs

示例10: SetWaitableTimer

 public static extern bool SetWaitableTimer(
     SafeHandle hTimer,
     ref long dueTime,
     int period,
     TimerAPCProc completionRoutine,
     IntPtr completionArg,
     bool fResume);
开发者ID:alberthoekstra,项目名称:PVBeanCounter,代码行数:7,代码来源:Win32WaitableTimer.cs

示例11: _HandleErrorCode

        private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
        {
            Exception exception = null;
            switch (errorCode)
            {
                case 2:
                    if (((context == null) || !(context is bool)) || !((bool) context))
                    {
                        if ((name != null) && (name.Length != 0))
                        {
                            return new FileNotFoundException(name);
                        }
                        return new FileNotFoundException();
                    }
                    if ((name != null) && (name.Length != 0))
                    {
                        return new DirectoryNotFoundException(name);
                    }
                    return new DirectoryNotFoundException();

                case 6:
                    return new ArgumentException(Environment.GetResourceString("AccessControl_InvalidHandle"));

                case 0x7b:
                    exception = new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), "name");
                    break;
            }
            return exception;
        }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:29,代码来源:FileSystemSecurity.cs

示例12: BindHandle

        /// <summary>
        ///     Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle, 
        ///     which is bound to the system thread pool.
        /// </summary>
        /// <param name="handle">
        ///     A <see cref="SafeHandle"/> object that holds the operating system handle. The 
        ///     handle must have been opened for overlapped I/O on the unmanaged side.
        /// </param>
        /// <returns>
        ///     <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which 
        ///     is bound to the system thread pool.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="handle"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     <paramref name="handle"/> has been disposed.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="handle"/> does not refer to a valid I/O handle.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="handle"/> refers to a handle that has not been opened 
        ///     for overlapped I/O.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="handle"/> refers to a handle that has already been bound.
        /// </exception>
        /// <remarks>
        ///     This method should be called once per handle.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>, 
        ///     it remains the responsibility of the caller to call <see cref="SafeHandle.Dispose"/>.
        /// </remarks>
        public static ThreadPoolBoundHandle BindHandle(SafeHandle handle)
        {
            if (handle == null)
                throw new ArgumentNullException("handle");

            if (handle.IsClosed || handle.IsInvalid)
                throw new ArgumentException(SR.Argument_InvalidHandle, "handle");

            try
            {
                // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall
                // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation.
                bool succeeded = ThreadPool.BindHandle(handle);
                Debug.Assert(succeeded);
            }
            catch (Exception ex)
            {   // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR.
                // We do not let either of these leak and convert them to ArgumentException to 
                // indicate that the specified handles are invalid.

                if (ex.HResult == System.__HResults.E_HANDLE)         // Bad handle
                    throw new ArgumentException(SR.Argument_InvalidHandle, "handle");

                if (ex.HResult == System.__HResults.E_INVALIDARG)     // Handle already bound or sync handle
                    throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, "handle");

                throw;
            }

            return new ThreadPoolBoundHandle(handle);
        }
开发者ID:jmhardison,项目名称:corefx,代码行数:70,代码来源:ClrThreadPoolBoundHandle.cs

示例13: CryptAcquireCertificatePrivateKey

        /// <summary>
        /// Obtains the private key for a certificate. This function is used to obtain access to a user's private key when the user's certificate is available, but the handle of the user's key container is not available. This function can only be used by the owner of a private key and not by any other user.
        /// If a CSP handle and the key container containing a user's private key are available, the CryptGetUserKey function should be used instead.
        /// </summary>
        /// <param name="pCert">The address of a CERT_CONTEXT structure that contains the certificate context for which a private key will be obtained.</param>
        /// <param name="dwFlags">A set of flags that modify the behavior of this function. This can be zero or a combination of one or more of <see cref="CryptAcquireCertificatePrivateKeyFlags"/> values.</param>
        /// <param name="pvParameters">
        /// If the <see cref="CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG"/> is set, then this is the address of an HWND. If the <see cref="CryptAcquireCertificatePrivateKeyFlags.CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG"/> is not set, then this parameter must be NULL.
        /// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP:  This parameter was named pvReserved and reserved for future use and must be NULL.
        /// </param>
        /// <param name="cryptHandle">
        /// Receives a safe handle to either CNG key handle of type NCRYPT_KEY_HANDLE or CryptoAPI provider handle of type HCRYPTPROV.
        /// </param>
        /// <returns>
        /// If the function succeeds, the return value is nonzero.
        /// If the function fails, the return value is zero.
        /// </returns>
        public static unsafe bool CryptAcquireCertificatePrivateKey(
            IntPtr pCert,
            CryptAcquireCertificatePrivateKeyFlags dwFlags,
            IntPtr pvParameters,
            out SafeHandle cryptHandle)
        {
            IntPtr cryptProvOrNCryptKey;
            uint keySpec;
            bool callerFreeProvOrNCryptKey;

            if (!CryptAcquireCertificatePrivateKey(
                pCert,
                dwFlags,
                (void*)pvParameters,
                out cryptProvOrNCryptKey,
                out keySpec,
                out callerFreeProvOrNCryptKey))
            {
                cryptHandle = AdvApi32.SafeCryptographicProviderHandle.Null;
                return false;
            }

            if (keySpec == CERT_NCRYPT_KEY_SPEC)
            {
                cryptHandle = new NCrypt.SafeKeyHandle(cryptProvOrNCryptKey, callerFreeProvOrNCryptKey);
            }
            else
            {
                cryptHandle = new AdvApi32.SafeCryptographicProviderHandle(cryptProvOrNCryptKey, callerFreeProvOrNCryptKey);
            }

            return true;
        }
开发者ID:AArnott,项目名称:pinvoke,代码行数:50,代码来源:Crypt32.Helpers.cs

示例14: UsbIOSync

        internal static bool UsbIOSync(SafeHandle dev, int code, Object inBuffer, int inSize, IntPtr outBuffer, int outSize, out int ret)
        {
            SafeOverlapped deviceIoOverlapped = new SafeOverlapped();
            ManualResetEvent hEvent = new ManualResetEvent(false);
            deviceIoOverlapped.ClearAndSetEvent(hEvent.SafeWaitHandle.DangerousGetHandle());
            ret = 0;

            if (!Kernel32.DeviceIoControlAsObject(dev, code, inBuffer, inSize, outBuffer, outSize, ref ret, deviceIoOverlapped.GlobalOverlapped))
            {
                int iError = Marshal.GetLastWin32Error();
                if (iError != ERROR_IO_PENDING)
                {
                    // Don't log errors for these control codes.
                    do
                    {
                        if (code == LibUsbIoCtl.GET_REG_PROPERTY) break;
                        if (code == LibUsbIoCtl.GET_CUSTOM_REG_PROPERTY) break;
                        UsbError.Error(ErrorCode.Win32Error, iError, String.Format("DeviceIoControl code {0:X8} failed:{1}", code, Kernel32.FormatSystemMessage(iError)), typeof(LibUsbDriverIO));
                    } while (false);

                    hEvent.Close();
                    return false;
                }
            }
            if (Kernel32.GetOverlappedResult(dev, deviceIoOverlapped.GlobalOverlapped, out ret, true))
            {
                hEvent.Close();
                return true;
            }
            UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetOverlappedResult failed.\nIoCtlCode:" + code, typeof(LibUsbDriverIO));
            hEvent.Close();
            return false;
        }
开发者ID:arvydas,项目名称:BlinkStickDotNet,代码行数:33,代码来源:LibUsbDriverIO.cs

示例15: _RegNotifyChangeKeyValue

 private static extern int _RegNotifyChangeKeyValue(
     SafeHandle hKey,
     bool bWatchSubtree,
     RegNotifyChange dwNotifyFilter,
     SafeHandle hEvent,
     bool fAsynchronous
 );
开发者ID:RussBaz,项目名称:PTVS,代码行数:7,代码来源:NativeMethods.cs


注:本文中的System.Runtime.InteropServices.SafeHandle类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。