Home > Software engineering >  Conversion error while trying to use CreateProcess Windows API
Conversion error while trying to use CreateProcess Windows API

Time:02-25

I am trying to run a C program that creates a process:

int main()
{
    HANDLE hProcess;
    HANDLE hThread;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    DWORD dwProcessId = 0;
    DWORD dwThreadId = 0;
    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));
    BOOL bCreateProcess = NULL;
    
    bCreateProcess = CreateProcessW(L"C:\\Windows\\System32\\notepad.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
                            
    if (bCreateProcess == FALSE) {
        cout << "Create Process Failed & Error No. " << GetLastError() << endl;
    }
    
    cout << "Process Creation Successful!" << endl;
    
    cout << "Process ID: " << pi.dwProcessId << endl;
    cout << "Thread ID: " << pi.dwThreadId << endl;
    cout << "GetProcessID: " << GetProcessId(pi.hProcess) << endl;
    cout << "GetThreadID: " << GetThreadId(pi.hThread) << endl;
    
    WaitForSingleObject(pi.hProcess, INFINITE);
    
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);

    return 0;
}

However, I returns the following error:

main.cpp(19): error C2664: 'BOOL CreateProcessW(LPCWSTR,LPWSTR,LPSECURITY_ATTRIBUTES,LPSECURITY_ATTRIBUTES,BOOL,DWORD,LPVOID,LPCWSTR,LPSTARTUPINFOW,LPPROCESS_INFORMATION)': cannot convert argument 9 from 'LPSTARTUPINFOW *' to 'LPSTARTUPINFOW'
main.cpp(27): note: Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
C:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\um\processthreadsapi.h(372): note: see declaration of 'CreateProcessW'

I am compiling it on Windows 10 using the following command:

cl.exe /EHsc main.cpp

Also, if you could please suggest some tutorials (courses, book, youtube channels, blogs, etc.) for Windows system programming.

CodePudding user response:

It seems you are compiling with Ansi strings rather than Wide strings, so STARTUPINFO becomes STARTUPINFOA, which is incompatible with CreateProcessW().

When I compile your code, I get error cannot convert argument 9 from 'STARTUPINFO *' to 'LPSTARTUPINFOW', which makes more sense than the error you posted.

Either change the compiler options or write STARTUPINFOW si; in your code.

  • Related