MSDN SafeHandle示例

问题描述 投票:8回答:1

也许是一个愚蠢的问题......我是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“句柄”变量? MySafeFileHandle的构造函数是私有的,甚至不把IntPtr作为参数!

关于CreateFile声明的评论说了些什么

... CLR的平台编组层将以原子方式将句柄存储到SafeHandle对象中。

我不确定我到底知道这意味着什么,有人可以解释一下吗?

c# .net
1个回答
3
投票

简短回答:这很神奇。运行时知道如何正确地将非托管句柄(只是指针大小的值)转换为SafeHandle并返回。

答案很长:它是足够先进的技术。具体来说,ILSafeHandleMarshaler是(非托管!)类,负责来回编组SafeHandles。 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字段都不是实际可访问的,但此代码不受可见性检查的限制。

© www.soinside.com 2019 - 2024. All rights reserved.