为什么当C中的等效工作正常时,DeviceIoControl会从C#中抛出错误21(设备未就绪)?

时间:2010-12-24 05:48:28

标签: c# c windows-mobile gps pinvoke

我正在尝试使用C#将IOCTL_SERVICE_REFRESH命令发送到GPS中间驱动程序服务,如下所示:

handle = CreateFile("GPD0:",
    GENERIC_READ,
    FILE_SHARE_READ | FILE_SHARE_WRITE,
    IntPtr.Zero,
    OPEN_EXISTING, 
    FILE_ATTRIBUTE_NORMAL, 
    IntPtr.Zero);

if (handle.ToInt32() == INVALID_HANDLE_VALUE)
{
    rc = Marshal.GetLastWin32Error();
    return rc;
}

int numBytesReturned = 0;

rc = DeviceIoControl(
    handle,
    IOCTL_SERVICE_REFRESH,
    null,
    0,
    null,
    0,
    ref numBytesReturned,
    IntPtr.Zero);

int error = Marshal.GetLastWin32Error();

GetLastWin32Error总是给我错误21(设备未准备好)。但是,从C ++生成的等效调用可以正常工作:

HANDLE hGPS = CreateFile(L"GPD0:", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hGPS != INVALID_HANDLE_VALUE) {
  BOOL ret = DeviceIoControl(hGPS,IOCTL_SERVICE_REFRESH,0,0,0,0,0,0);
  DWORD err = GetLastError();       
}

我怀疑PInvoke签名存在问题,但我似乎找不到任何错误:

[DllImport("coredll.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
public static extern int DeviceIoControl(
    IntPtr hDevice,
    uint dwIoControlCode,
    byte[] lpInBuffer,
    int nInBufferSize,
    byte[] lpOutBuffer,
    int nOutBufferSize,
    ref int lpBytesReturned,
    IntPtr lpOverlapped);

[DllImport("coredll.dll", SetLastError = true)]
public static extern IntPtr CreateFile(
    String lpFileName,
    uint dwDesiredAccess,
    uint dwShareMode,
    IntPtr attr,
    uint dwCreationDisposition,
    uint dwFlagsAndAttributes,
    IntPtr hTemplateFile);

我在这里缺少什么?

0 个答案:

没有答案