سؤال

I'm currently trying to use CreateProcess with the Path, Arguments and Environment Variables. My variables are stored in strings.

In the below example filePath and cmdArgs work fine, but I cannot get the envVars to work.

std::string filePath = "C:\\test\\DummyApp.exe";
std::string cmdArgs  = "Arg1 Arg2 Arg3";
std::string envVars  = "first=test\0second=jam\0";  // One

//LPTSTR testStr = "first=test\0second=jam\0";      // Two

CreateProcess(
   LPTSTR(filePath.c_str()),           //path and application name
   LPTSTR(cmdArgs.c_str()),            // Command line
   NULL,                               // Process handle not inheritable
   NULL,                               // Thread handle not inheritable
   TRUE,                               // Set handle inheritance
   0,                                  // Creation flags
   LPTSTR(envVars.c_str()),            // environment block
   //testStr                      //this line works
   NULL,                               // Use parent's starting directory 
   &si,                                // Pointer to STARTUPINFO structure
   &pi )                               // Pointer to PROCESS_INFORMATION structure

)

When I run this code the error that comes back is "error 87: The parameter is incorrect".

What I don't understand is that if I comment out the line labeled "one" and replace it with the line labeled "two" (and make the matching swap in the function call) then it works correctly.

هل كانت مفيدة؟

المحلول

The constructor of std::string you used will copy "first=test\0second=jam\0" until first \0 (C-style string).

To pass all the string use another constructor:

std::string envVars("first=test\0second=jam\0", 22);
                     ^^^^^^^^^^^^^^^^^^^^^^^^   ^
                                                |
                           22 characters -------+
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top