【问题标题】:Windows API DiInstallDevices causes ExceptionWindows API DiInstallDevices 导致异常
【发布时间】:2013-07-02 09:43:13
【问题描述】:

我正在尝试访问 Win32 API 以在设备上安装驱动程序。我正在使用setupapi.h 中的一堆函数,所有这些都运行良好。在这段代码中,我使用它们来获取调用此安装函数所需的参数(即设备和驱动程序的名称/指针)(它不是setupapi.h 的一部分,而是newdev.h 的一部分) .
以下是我的 P/Invoke 和实际的方法调用。我已经使用调试器进行了调查,我很确定我从 SetupAPI 获得的信息是正确的。 (即,参数很好,我的意思是它们确实包含所需的信息。)

IntPtr deviceInfoSet;
Win32SetupApi.SP_DEVINFO_DATA devInfoData;
GetDeviceHandleFromMatch(deviceInfo, out deviceInfoSet, out devInfoData);
Win32SetupApi.SP_DRVINFO_DATA drvInfoData;
GetDriverHandleFromMatch(driverInstance, deviceInfoSet, devInfoData, out drvInfoData);

try
{
   bool needReboot = false;
   Win32SetupApi.DiInstallDevice(
      IntPtr.Zero,
      deviceInfoSet,
      devInfoData,
      drvInfoData,
      0,
      ref needReboot);
}
catch (Exception ex)
{
   throw;
}
[DllImport("newdev.dll", SetLastError = true)]
  public static extern bool DiInstallDevice(
     IntPtr hParent, 
     IntPtr lpInfoSet, 
     SP_DEVINFO_DATA DeviceInfoData,
     SP_DRVINFO_DATA DriverInfoData,
     UInt32 Flags, 
     [MarshalAs(UnmanagedType.Bool)] ref bool NeedReboot);

我得到的异常是“尝试读/写受保护的内存”,没有通过 LastWin32Error 提供的信息。

非常感谢您对这里可能发生的事情的任何想法!

【问题讨论】:

    标签: c# c++ winapi pinvoke driver


    【解决方案1】:

    知道了!

    [DllImport("newdev.dll", SetLastError = true)]
    public static extern bool DiInstallDevice(
        IntPtr hParent, 
        IntPtr lpInfoSet, 
        ref SP_DEVINFO_DATA DeviceInfoData,
        ref SP_DRVINFO_DATA DriverInfoData,
        UInt32 Flags, 
        ref bool NeedReboot);
    

    结构必须按照here 的描述通过引用传递。不确定 Bool 编组是否错误,但我也删除了它。
    不敢相信这需要几个小时才能再次弄清楚,一定要喜欢 P/Invoke。希望这对其他人也有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2012-10-25
      相关资源
      最近更新 更多