คำตอบ Calling DhcpEnumServers from .Net

  • 1 พฤษภาคม 2555 19:25
     
      มีโค้ด

    I am attempting to call the routine DhcpEnumServers that exists in dhcpsapi.dll from a C# application. This call should return a status of 0 to indicate success however it is returning 87 which is not listed as a valid return code for this call. A status of 87 is the Windows error value for invalid argument so I'm assuming that I have a problem with the marshalling of arguments for the interop call. I've provided the smallest code sample that I can to reproduce the problem. Any help would be greatly appreciated.

    using System;
    using System.Runtime.InteropServices;
    
    namespace QueryDhcp
    {
        class Program
        {
            [DllImport("dhcpsapi.dll", SetLastError = true, CharSet = CharSet.Ansi)]
            public static extern uint DhcpEnumServers(
                uint flags,
                ref uint idInfo,
                out IntPtr servers,
                ref uint callbackFn,
                ref uint callbackData
                );
    
            static void Main(string[] args)
            {
                uint nr = 0;
                IntPtr svrs;
                uint dhcpResult = DhcpEnumServers(nr, ref nr, out svrs, ref nr, ref nr);
            }
        }
    }
    
    
    

ตอบทั้งหมด

  • 1 พฤษภาคม 2555 20:00
     
     คำตอบ

    Try this definition:

    [DllImport"dhcpsapi.dll"SetLastError = trueCharSet = CharSet.Unicode )]
    public static extern uint DhcpEnumServers(
             uint Flags,
             IntPtr IdInfo,
             out IntPtr Servers,
             IntPtr CallbackFn,
             IntPtr CallbackData
             );

    . . . .

    IntPtr svrs;
    uint dhcpResult = DhcpEnumServers0IntPtr.Zeroout svrsIntPtr.ZeroIntPtr.Zero );

    If now you receive other error codes, see http://msdn.microsoft.com/en-us/library/windows/desktop/aa363378(v=vs.85).aspx.

    • ทำเครื่องหมายเป็นคำตอบโดย Brew Guy 1 พฤษภาคม 2555 20:43
    •  
  • 1 พฤษภาคม 2555 20:44
     
     

    That worked.

    Thanks for the help.