Parhaps a silly question... I'm new to C# and .Net.
In the example for the SafeHandle class (C#) on MSDN, the code made me scratch my head a bit.
[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);
My question is: How does the Win32 HANDLE from the C function CreateFile
get into the MySafeFileHandle
objects protected IntPtr
"handle" variable? The constructor of MySafeFileHandle
is private and doesn't even take an IntPtr
as an argument!
The comment just over the CreateFile
statement says something about
… the CLR's platform marshalling layer will store the handle into the SafeHandle object in an atomic fashion.
I'm not sure I know exactly what this means, can anyone explain please?