Passing enum to pInvoke api call

S

Steve Richter

when I call a win32 api like CreateFile, I would like to be able to
pass an enumerated value as the parameter value:
hFile = CreateFile(
InPath, GENERIC_READ,
ShareMode.Read, // this is an enum
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

I know I can cast the enum:
(uint) ShareMode.Read

but I consider that redundant ( and casting makes me nervous! ).

In C#, can I specify that the enum can always be converted to a (uint),
allowing the compiler to implicitly case the enum to a uint?

thanks,

-Steve



public enum ShareMode
{
NotShared = 0,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004
}

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

Marc Gravell

Well, I can't remember off-hand, but have you tried declaring the enum
as " : uint" and declaring the dll call with "ShareMode shareMode"
instead of "uint shareMode"? If this doesn't work, another option is to
at least hide it from the outside world by having the PInvoke call
private, and having all public versions accept the enum, which you then
cast when calling the dll. However, there is no reason for this cast to
make you nervous - especially when dealing with PInvoke this is fairly
common.

Specific to this problem, have you checked you can't do what you want
with File.Open / File.Create and the associated overloads (looking
especially at the FileMode and FileShare options)?

Marc
 

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

Top