1

我正在尝试将一些用 C 编写的代码翻译成 C#(Compact Framework 2.0)(适用于带有 RFID 阅读器的 Windows CE 设备)。

在 C 中,这个系统调用工作正常,但在 C# 中不起作用:

C语言代码

HANDLE m_Power =NULL; //<-- This HANDLE is set correctly before call "ControlDevice"
int ControlDevice(int device, BYTE power_state)
{
bool bRet;
    DWORD tcBuffer2,dwBytesReturned;
    unsigned int a = sizeof(power_state);
    bRet=DeviceIoControl(   m_Power, 
                device, 
                &power_state, 
                sizeof(power_state),  
                (PBYTE)&tcBuffer2, 
                sizeof(DWORD),
                &dwBytesReturned, 
                NULL);
    if(bRet)
        return 1;
    else
        return -1;
}

C# 中的代码

int ControlDevice(int device, byte[] power_state)
    {
        try
        {
            bool bRet = false;
            int bytesReturned = 0;
            byte[] tcBuffer2 = new byte[1];
            tcBuffer2[0] = 0;

            bRet = Device_WinApi.DeviceIoControlCE(m_Power,
                                    device,
                                    power_state,
                                    (int)Marshal.SizeOf(power_state),
                                    tcBuffer2,
                                    (int)Marshal.SizeOf(tcBuffer2),
                                    out bytesReturned,
                                    IntPtr.Zero);
            if (bRet)

                return 1;
            else
            {
                int LastError = Device_WinApi.GetLastError();
                return -1;
            }
        }
        catch (Exception e)
        {
            return -1;
        }
    }

DLL是这样导入的:

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("coredll.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
internal static extern bool DeviceIoControlCE(
                IntPtr hDevice,
                long dwIoControlCode, 
                byte[] lpInBuffer,
                int nInBufferSize,
                byte[] lpOutBuffer,
                int nOutBufferSize,
                out int lpBytesReturned,
                IntPtr lpOverlapped);

在当前的 C# 实现中,bRet = false,I 应该为 true,因为这是在 C 中获得的值

这也返回零:

 int LastError = Device_WinApi.GetLastError()

任何帮助将不胜感激!

感谢您提前抽出时间!!

4

0 回答 0