Open a COM port in C++ with number higher that 9

白昼怎懂夜的黑 提交于 2019-12-29 06:17:39

问题


I am using a COM port in C++. I can not open COM ports with a higher number than 9, for example 10. This is function used for COM port detection:

WCHAR port_name[7];
WCHAR num_port[4];        

for (i=1; i<256; i++)
{
    bool bSuccess = false;

    wcscpy(port_name,L"COM");
    wcscat(port_name,_itow(i,num_port,10));

    HANDLE hPort;

    //Try to open the port
    hPort = CreateFile(L"COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
    //hPort = CreateFile(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

    if (hPort == INVALID_HANDLE_VALUE)
    {
        DWORD dwError = GetLastError();

        //Check to see if the error was because some other application had the port open
        if (dwError == ERROR_ACCESS_DENIED)
        {
            bSuccess = TRUE;
            j=j+1;  
        }
    }
    else   //The port was opened successfully
    {            
        bSuccess = TRUE;
        j=j+1;

        CloseHandle(hPort);   //closing the port
    }

    if (bSuccess)array_ports[j]=i;

}

I can not understand why for example COM10, throws FFFFFFFF back to HANDLE hPort.

hPort = CreateFile(L"COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

COM9, COM8, COM7, etc. works fine,

hPort = CreateFile(L"COM9", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

It there a solution for this problem?


回答1:


It is a bug and the resolution is to use the string

\\.\COM10

hPort = CreateFile("\\\\.\\COM10", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

check this article.




回答2:


You need to use the following format for COM ports greater than 9:

\\\\.\\COM%d

Where %d is a printf-substitution for the port number.

Why? Well, this accesses the global NT object space, where all objects are stored. Windows only knows to alias COM0-9 in the fashion you're using it for DOS support; beyond that, they act like ordinary devices, which are accessed this way.

To explore the NT object space, I recommend WinObj which basically lets you browse around. \.\ is mapped to GLOBAL?? in this tree (as are some other areas, actually. The rest of the tree requires you have NT's, as opposed to Win32's, view of the system).

And just in case you didn't know, INVALID_HANDLE_VALUE is defined as 0xffffff... - this usually occurs when an open fails.



来源:https://stackoverflow.com/questions/11775185/open-a-com-port-in-c-with-number-higher-that-9

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!