How do I fix “The program issued a command but the command length is incorrect.” error when calling Process32First()?

扶醉桌前 提交于 2019-12-11 03:38:47

问题


GetLastError tells me I'm getting the "The program issued a command but the command length is incorrect." error when calling Process32First() (see code below). I found one post that looked helpful (http://social.msdn.microsoft.com/Forums/is/vcgeneral/thread/6f43716f-fdd3-4c92-bfba-6a23178c32bf), but I'm not sure if this is my problem.

I've tried building a program that includes only "stdafx.h", <iostream>, <Windows.h> and <TlHelp32.h> to test __alignof(PROCESSENTRY32), but I still get a value of 4. Not sure if that's correct or not.

Here is the code that's failing:

HANDLE hProcess;
PROCESSENTRY32 pe32;

cout << "Size of PROCESSENTRY32 is: " << sizeof(PROCESSENTRY32) << "\r\n"; // 556
cout << "Align of PROCESSENTRY32 is: " << __alignof(PROCESSENTRY32) << "\r\n"; // 4

if ( !(hProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) ) {
    cout << "CreateToolhelp32Snapshot() failed: " << GetLastError() << "\r\n";
    return (HANDLE)NULL;
} else {
    cout << "CreateToolhelp32Snapshot() succeeded.\r\n";
}

if (Process32First(hProcess, &pe32)) {
    do {
        cout << pe32.th32ModuleID;
    } while (Process32Next(hProcess, &pe32));
} else {
    cout << "Process32First() failed: " << GetLastError() << "\r\n";
}

回答1:


From the docs on Process32First:

The calling application must set the dwSize member of PROCESSENTRY32 to the size, in bytes, of the structure.

I don't see you doing that in your code, and I suspect it's the problem. Fix it:

pe32.dwSize = sizeof pe32;
if (Process32First(...))

The reasoning behind this mandatory action for many of the winapi structures is for the flexibility to add more onto the structure later on, but let functions know which version is being used by checking against known sizes of previous versions.



来源:https://stackoverflow.com/questions/14492352/how-do-i-fix-the-program-issued-a-command-but-the-command-length-is-incorrect

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