C#如何使用DeviceIoControl控制端口输出??[
我现在用的是并口。地址是378h,我用c++写了一小段程序就能跑通,在并口上能测到输出,但是用C#写的同样功能的程序来测试,并口就没有任何反应,把程序贴上来,麻烦大家给看一下,谢谢了~~~
下面是C++的
int main(){ HANDLE hDevice = CreateFile("\\\\.\\HelloDDK", GENERIC_READ | GENERIC_WRITE, 0, // share mode none NULL, // no security OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); // no template if (hDevice == INVALID_HANDLE_VALUE) { return 1; } else { printf("Successed to obtain file handle to device."); } DWORD dwOutput; DWORD outputBuffer[8]; DWORD inputBuffer[1]; int i,j; //开始输出数据 do{ inputBuffer[0] = 0x00600378; //Output Data Register DeviceIoControl(hDevice, WRITE_PORT, inputBuffer, sizeof(inputBuffer), NULL, 0, &dwOutput, NULL); for (i=0;i<850;i++){;} }while(1); CloseHandle(hDevice); printf("!!!"); getchar(); return 0;}
#region DLLImport //DeviceIoControl在C#中的引用和定义 [DllImport("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)] internal static extern int DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, uint[] lpInBuffer, int nInBufferSize, byte[] lpOutbuffer, int nOutBufferSize, ref int lpByteReturned, IntPtr lpOverlapped ); [DllImport("kernel32.dll")] private static extern IntPtr CreateFile( string lpFileName, uint dwDesireAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile ); [DllImport("kernel32.dll", SetLastError = true)] static extern int CloseHandle(IntPtr hObject); private const uint GENERIC_READ = 0x80000000; private const uint GENERIC_WRITE = 0x40000000; private const int OPEN_EXISTING = 3; #endregion static void Main(string[] args) { //设置的有关GPIO的全局变量 IntPtr gpioDevice = new IntPtr(); int bytesReturned = 0; gpioDevice = CreateFile("\\\\.\\HelloDDK", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (gpioDevice == (IntPtr)(-1)) { //暂时不处理 Console.WriteLine("连接GPIO设备失败"); } else { while (true) { uint[] data = new uint[1]; data[0] = 0x00600378; DeviceIoControl(gpioDevice, 0x01, data, sizeof(uint), null, 0, ref bytesReturned, IntPtr.Zero); for (int j = 0; j < 850; j++) { } Console.WriteLine(DeviceIoControl(gpioDevice, 0x02, data, 4, null, 0, ref bytesReturned, IntPtr.Zero)); Console.WriteLine("******"); } } }
[解决办法]
[DllImport("kernel32.dll", EntryPoint = "DeviceIoControl", SetLastError = true)]
internal static extern int DeviceIoControl(
IntPtr hDevice,
uint dwIoControlCode,
uint[] lpInBuffer, //C#的数组不能当指针用
int nInBufferSize,
byte[] lpOutbuffer, //
int nOutBufferSize,
ref int lpByteReturned,
IntPtr lpOverlapped
);