一个愚蠢的问题……我是C#和.Net的新手。
In the example for the SafeHandle class (C#) on MSDN,该代码使我有些挠头。
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
internal class MySafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private MySafeFileHandle()
: base(true)
{}
// other code here
}
[SuppressUnmanagedCodeSecurity()]
internal static class NativeMethods
{
// other code...
// Allocate a file object in the kernel, then return a handle to it.
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
internal extern static MySafeFileHandle CreateFile(String fileName,
int dwDesiredAccess, System.IO.FileShare dwShareMode,
IntPtr securityAttrs_MustBeZero, System.IO.FileMode
dwCreationDisposition, int dwFlagsAndAttributes,
IntPtr hTemplateFile_MustBeZero);
// other code...
}
// Later in the code the handle is created like this:
MySafeFileHandle tmpHandle;
tmpHandle = NativeMethods.CreateFile(fileName, NativeMethods.GENERIC_READ,
FileShare.Read, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
我的问题是:C函数CreateFile
的Win32 HANDLE如何进入MySafeFileHandle
受保护的IntPtr
“ handle”变量的对象中? MySafeFileHandle
的构造函数是私有的,甚至不使用IntPtr
作为参数!
CreateFile
语句上方的评论中有一些关于
... CLR的平台编组层将以原子方式将句柄存储到SafeHandle对象中。
我不确定我确切知道这是什么意思,有人可以解释一下吗?
答案 0 :(得分:3)
简短的回答:这很神奇。运行时知道如何正确地将非托管句柄(只是指针大小的值)转换为SafeHandle
并返回。
长答案:这是足够先进的技术。具体来说,ILSafeHandleMarshaler
是(非托管!)类,负责来回地编组SafeHandle
。 source code有助于总结该过程:
// 1) create local for new safehandle // 2) prealloc a safehandle // 3) create local to hold returned handle // 4) [byref] add byref IntPtr to native sig // 5) [byref] pass address of local as last arg // 6) store return value in safehandle
它发出的将非托管句柄加载到安全句柄中的代码实际上是托管代码,尽管托管代码愉快地忽略了可访问性。它获取并调用默认构造函数以创建新实例:
MethodDesc* pMDCtor = pMT->GetDefaultConstructor();
pslIL->EmitNEWOBJ(pslIL->GetToken(pMDCtor), 0);
pslIL->EmitSTLOC(dwReturnHandleLocal);
然后直接设置SafeHandle.handle
字段:
mdToken tkNativeHandleField =
pslPostIL->GetToken(MscorlibBinder::GetField(FIELD__SAFE_HANDLE__HANDLE));
...
// 6) store return value in safehandle
pslCleanupIL->EmitLDLOC(dwReturnHandleLocal);
pslCleanupIL->EmitLDLOC(dwReturnNativeHandleLocal);
pslCleanupIL->EmitSTFLD(tkNativeHandleField);
实际上不能访问构造函数和handle
字段,但是此代码不受可见性检查。