QueryDosDeviceW
returns 0 when called from a source other than the main thread. Why?
I used Visual Studio 2022 (v143) platform.
Below is the test code and output.
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <fileapi.h>
std::vector<std::string> GetAvailableSerialPortsNames() {
std::vector<std::string> com_names;
TCHAR lp_target_path[5000];
for (int i = 0; i <= 255; i++) { // checking ports from COM0 to COM255
std::string com_name = "COM" + std::to_string(i); // converting to COM0, COM1, COM2
DWORD Test
= QueryDosDeviceW((LPCWSTR)(
std::wstring(com_name.begin(), com_name.end()).c_str()),
(LPWSTR)lp_target_path, 5000);
if (Test != 0)
com_names.push_back(com_name);
if (::GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
lp_target_path[10000]; // in case the buffer got filled, increase size of the buffer.
continue;
}
}
return com_names;
}
int main(void) {
auto serials = GetAvailableSerialPortsNames();
std::cout << "Querying in main thread. Ports count=" << serials.size() << std::endl;
for (auto s : serials) std::cout << s << std::endl;
std::thread([]() {
auto serials = GetAvailableSerialPortsNames();
std::cout << "Querying in other thread. Ports count=" << serials.size() << std::endl;
for (auto s : serials) std::cout << s << std::endl;
}).detach();
std::this_thread::sleep_for(std::chrono::seconds(3));
return 0;
}
Querying in main thread. Ports count=3
COM1
COM3
COM4
Querying in other thread. Ports count=0