c#FindFirstDevice Marshaling

时间:2013-01-18 14:51:30

标签: c# windows-ce marshalling

我在winCE 6.0版本上运行了一个c#应用程序。我需要在运行时卸载/重新加载SD卡驱动程序。我试图通过调用FindFirstDevice,然后调用DeactivateDevice / ActivateDeviceEX调用来做到这一点。我的问题是FindFirstDevice()调用总是失败。我认为这是我编组第二个参数的方式的问题。谁能告诉我我做错了什么?这是代码:

  [DllImport("coredll.dll", SetLastError = true)]
  public static extern int FindFirstDevice(DeviceSearchType
  searchType, IntPtr searchParam, ref DEVMGR_DEVICE_INFORMATION pdi);

  public bool MountSDCardDrive(string mRegPath)
  {
     const int INVALID_HANDLE_VALUE = -1;

     int handle = INVALID_HANDLE_VALUE;
     DeviceSearchType searchType = DeviceSearchType.DeviceSearchByDeviceName;

     DEVMGR_DEVICE_INFORMATION di = new DEVMGR_DEVICE_INFORMATION();
     di.dwSize = (uint)Marshal.SizeOf(typeof(DEVMGR_DEVICE_INFORMATION));

     string searchParamString = "*";
     IntPtr searchParam = Marshal.AllocHGlobal(searchParamString.Length);
     Marshal.StructureToPtr(searchParamString, searchParam, false);

     handle = FindFirstDevice(searchType, searchParam, ref di);
     if (handle == INVALID_HANDLE_VALUE)
     {
        // Failure - print error
        int hFindFirstDeviceError = Marshal.GetLastWin32Error();

        using (StreamWriter bw = new StreamWriter(File.Open(App.chipDebugFile, FileMode.Append)))
        {
           String iua = "DevDriverInterface: error from FindFirstDevice: " + hFindFirstDeviceError.ToString();
           bw.WriteLine(iua);
        }
        return false;
     }

... (rest of code)

如果我将行Marshal.StructureToPtr(searchParamString, searchParam, false);更改为searchParam = Marshal.StringToBSTR(searchParamString);"我最终会收到错误1168(ERROR_NOT_FOUND)而不是18(不再有文件)。

注意我的意图是使用searchParamString" SDH1"当我得到这个工作。我目前正在使用searchParamString" *"为了看到返回的内容并排除特定的字符串值。

感谢您提供任何帮助 - 林恩

1 个答案:

答案 0 :(得分:1)

FindFirstDevice必须与FindNextDevice一起使用(它使用FindFirstDevice返回的句柄作为其第一个参数,如果找到另一个设备则返回TRUE),因为你必须迭代所有设备才能找到好的设备...并且为此,您必须比较结构中的szLegacyName值。

卸下:

IntPtr searchParam = Marshal.AllocHGlobal(searchParamString.Length);

仅使用:

IntPtr searchParam = Marshal.StringToBSTR(searchParamString);

由于该方法已经提供了分配必要的内存(记得在finally块中使用Marshal.FreeBSTR()以释放该内存空间)。

您的结构应如下所示:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] 
public struct DEVMGR_DEVICE_INFORMATION 
{ 
    public UInt32 dwSize; 
    public IntPtr hDevice; 
    public IntPtr hParentDevice; 

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)] 
    public String szLegacyName; 

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] 
    public String szDeviceKey; 

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] 
    public String szDeviceName; 

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] 
    public String szBusName; 
}