本文整理汇总了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.");
}
}
示例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);
}
示例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);
}
}
示例4: CloseInvalidOutSafeHandle
internal static void CloseInvalidOutSafeHandle(SafeHandle handle)
{
if (handle != null)
{
handle.SetHandleAsInvalid();
}
}
示例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());
}
示例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;
}
示例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);
示例8: GetDescriptor
public abstract bool GetDescriptor(SafeHandle interfaceHandle,
byte descriptorType,
byte index,
ushort languageID,
IntPtr buffer,
int bufferLength,
out int lengthTransferred);
示例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());
}
示例10: SetWaitableTimer
public static extern bool SetWaitableTimer(
SafeHandle hTimer,
ref long dueTime,
int period,
TimerAPCProc completionRoutine,
IntPtr completionArg,
bool fResume);
示例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;
}
示例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);
}
示例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;
}
示例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;
}
示例15: _RegNotifyChangeKeyValue
private static extern int _RegNotifyChangeKeyValue(
SafeHandle hKey,
bool bWatchSubtree,
RegNotifyChange dwNotifyFilter,
SafeHandle hEvent,
bool fAsynchronous
);