P/Invoke, CreateFile and SafeFileHandle

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
 
T

Tom Porterfield

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top