Passing enum to pInvoke api call

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Steve Richter

    #1

    Passing enum to pInvoke api call

    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("kern el32.dll", SetLastError = true)]
    static extern unsafe System.IntPtr CreateFile(
    string lpFileName,
    uint dwDesiredAccess ,
    uint dwShareMode,
    IntPtr lpSecurityAttri butes,
    uint dwCreationDispo sition,
    uint dwFlagsAndAttri butes,
    IntPtr hTemplateFile);

  • Marc Gravell

    #2
    Re: Passing enum to pInvoke api call

    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

    Comment

    Working...