P/Invoke, CreateFile and SafeFileHandle

  • Thread starter Thread starter Bob Gray
  • Start date Start date
B

Bob Gray

Hi,

Can anyone explain how P/Invoke is able to cast the 32-bit HANDLE value
returned from CreateFile (for example) to a SafeFileHandle object?

Have a look at this code snippet from the .NET Framework Reference:

-----------------------------------------------------------
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);


private SafeFileHandle handleValue = null;


handleValue = CreateFile(
Path,
GENERIC_WRITE,
0,
IntPtr.Zero,
OPEN_EXISTING,
0,
IntPtr.Zero);
-----------------------------------------------------------

Is there some kind of behind-the-scenes stuff going on with P/Invoke to
generate the extra code that puts the returned HANDLE into the handle
member of the SafeFileHandle..?


-Bob
 
Bob said:
Hi,

Can anyone explain how P/Invoke is able to cast the 32-bit HANDLE value
returned from CreateFile (for example) to a SafeFileHandle object?

Have a look at this code snippet from the .NET Framework Reference:

<snipped for brevity>

Is there some kind of behind-the-scenes stuff going on with P/Invoke to
generate the extra code that puts the returned HANDLE into the handle
member of the SafeFileHandle..?

Yes, the CLR's platform invoke marshaling layer stores the HANDLE returned
by CreateFile into the SafeFileHandle object.
 
Back
Top