我阅读了很多关于SafeHandle
但IDiposable
我仍然不明白是否应该在 C# 中使用 SafeHandle 和 CloseHandle。
IntPtr、SafeHandle 和 HandleRef - 解释
https://blog.benoitblanchon.fr/safehandle/。
第一个来源类似于我的问题,但它没有回答我的问题。
假设我有以下 3 个从 Internet 获得的不同示例:
// Example 1
byte[] temp = new byte[IntPtr.Size];
fixed (byte* p = temp)
{
IntPtr SectionHandle = new IntPtr(p);
LARGE_INTEGER MaximumSize = new LARGE_INTEGER();
MaximumSize.LowPart = pNTHeader->OptionalHeader.SizeOfImage;
status = NtCreateSection(
SectionHandle,
SectionAccess.SECTION_MAP_EXECUTE | SectionAccess.SECTION_MAP_READ | SectionAccess.SECTION_MAP_WRITE,
IntPtr.Zero,
ref MaximumSize,
MemoryProtectionConstants.PAGE_EXECUTE_READWRITE,
AllocationTypes.SEC_COMMIT,
IntPtr.Zero);
}
// Example 2
IntPtr hFile = CreateFile(
path,
GenericRights.GENERIC_READ,
FileFlags.FILE_SHARE_DELETE | FileFlags.FILE_SHARE_READ | FileFlags.FILE_SHARE_WRITE,
IntPtr.Zero,
FileCreationFlags.OPEN_EXISTING,
FileFlags.FILE_ATTRIBUTE_NORMAL,
IntPtr.Zero);
if (hFile == INVALID_HANDLE_VALUE)
return false;
// Example 3
IntPtr hMap = CreateFileMapping(
hFile,
IntPtr.Zero,
MemoryProtectionConstants.PAGE_READONLY,
0,
0,
IntPtr.Zero);
if (hMap == IntPtr.Zero)
return false;
这些示例是 Windows API,因此它们是非托管的。我不明白的是:
1)所有 3 个示例是否应该使用 SafeHandle 而不是 IntPtr,因为它们是非托管的,如果其中一个不应该,为什么?
2) 我发现 CloseHandle 在 C/C++ 中是一个很好的做法,但在 C# 中我不知道垃圾收集器最终是否会自动关闭句柄?在上面的例子中应该使用 CloseHandle 吗?为什么?
3) 第一个示例使用非托管byte*
在堆上分配内存。这个过程可以通过不使用非托管指针来完成吗?下面的代码是我的猜测,你怎么看?
IntPtr SectionHandle = Marshal.AllocateHGlobal(sizeof(int));
... code ...
Marshal.FreeHGlobal(SectionHandle);
编辑: 发布我编辑的代码:
[SecurityCritical]
public sealed class SafeHandleBuffer : SafeBuffer
{
public SafeHandleBuffer()
: base(true)
{
handle = Marshal.AllocHGlobal(IntPtr.Size);
}
public int GetValue() =>
Marshal.ReadInt32(handle);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
return true;
}
}
public sealed class SafeHandleToken : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeHandleToken()
: base(true)
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle() =>
CloseHandle(handle);
}
// Including the IDisposable implementation in the class where the next example calls are found
private SafeHandleToken _fileHandle, _mappingHandle;
private SafeHandleBuffer _sectionHandle;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
protected virtual void Dispose(bool disposing)
{
if (_fileHandle != null && !_fileHandle.IsInvalid)
{
_fileHandle.Dispose();
}
if (_mappingHandle != null && !_mappingHandle.IsInvalid)
{
_mappingHandle.Dispose();
}
if (_sectionHandle != null && !_sectionHandle.IsInvalid)
{
_sectionHandle.Dispose();
}
}
// Example 1
SafeHandleBuffer tempHandle = new SafeHandleBuffer();
LARGE_INTEGER MaximumSize = new LARGE_INTEGER();
MaximumSize.LowPart = pNTHeader->OptionalHeader.SizeOfImage;
status = NtCreateSection(
tempHandle,
SectionAccess.SECTION_MAP_EXECUTE | SectionAccess.SECTION_MAP_READ | SectionAccess.SECTION_MAP_WRITE,
IntPtr.Zero,
ref MaximumSize,
MemoryProtectionConstants.PAGE_EXECUTE_READWRITE,
AllocationTypes.SEC_COMMIT,
IntPtr.Zero);
// Example 2
SafeHandleToken tempHandle = CreateFile(
path,
GenericRights.GENERIC_READ,
FileShare.ReadWrite | FileShare.Delete,
IntPtr.Zero,
FileMode.Open,
FileAttributes.Normal,
IntPtr.Zero);
Thread.Sleep(500);
_fileHandle = tempHandle;
if (_fileHandle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Example 3
tempHandle = CreateFileMapping(
_fileHandle,
IntPtr.Zero,
(uint)MemoryProtectionConstants.PAGE_READONLY | (uint)AllocationTypes.SEC_IMAGE,
0,
0,
IntPtr.Zero);
Thread.Sleep(500);
_mappingHandle = tempHandle;
if (_mappingHandle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
你认为我做的一切都好吗?应该SafeHandle
在每个 Windows API 上使用,比如GetModuleHandle
, GetProcAddress
,MapViewOfFile
还有一些我现在不记得了。他们中的一些人正在返回LPVOID
。