Help with CreateProcess

I am trying to write a program that takes user input for what executable to run and any arguments, passes it to my function that contains CreateProcess and executes the executable the user specified (e.g. c:\\windows\\system32\\notepad.exe test.txt). If I hard code the values doing something like if (!CreateProcess(TEXT("c:\\windows\\system32\\notepad.exe"), ... than it works. However, I have been unable to get it working by using my arguments. As I understand, the first argument to CreateProcess needs to be a LPCTSTR and the second a LPWSTR. I tried using c_str() to convert but not sure if this is the correct way to do it. The code compiles, but always results in CreateProcess failing. Any ideas what I am missing here? Thanks for any help in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
std::string launchExecutable(const std::string& program, const std::string& exeArgs)
{
	STARTUPINFO sInfo;
	PROCESS_INFORMATION pInfo;

	ZeroMemory(&sInfo, sizeof(sInfo));
	sInfo.cb = sizeof(sInfo);
	ZeroMemory(&pInfo, sizeof(pInfo));


	// Convert strings to proper format for CreateProcess
	LPCTSTR appName = (LPCTSTR)program.c_str();
	LPWSTR args = (LPWSTR)exeArgs.c_str();


	// Start the child process. 
	if (!CreateProcess(appName,   // No module name (use command line)
		args,        // Command line arguments argv[1]
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		0,              // No creation flags
		NULL,           // Use parent's environment block
		NULL,           // Use parent's starting directory 
		&sInfo,            // Pointer to STARTUPINFO structure
		&pInfo)           // Pointer to PROCESS_INFORMATION structure
		)
	{
		printf("CreateProcess failed (%d).\n", GetLastError());
		std::string launchExecutableResult = "CreateProcess failed";
		return launchExecutableResult;
	}
	else
	{
		std::string launchExecutableResult = "CreateProcess successful";
		return launchExecutableResult;
	}

}
There're two things you need to do:

a) You can't cast a string.c_str() to LPCTSTR, in unicode environment, it's wrong.
b) You can't cast a c_str() returned value to LPTSTR (same as LPWSTR in unicode environment), you need allocate it.
Thanks, how should I handle this situation then? Do I need to convert the string into something else that can then be converted to a LPCTSTR value? I apologize for the lack of understanding but I am still very new to C++
Ended up using ShellExecuteA to get this working.
For a), you could use CreateProcessA, so just like ShellExecuteA, you could pass const char* (ansi form of LPCTSTR).
For b), I have some snippet code, though not safe (assume you're using CreateProcessA)

1
2
3
char args[1000];
strcpy(args, exeArgs.c_str());
if (CreateProcessA(appName, args, ...))

Topic archived. No new replies allowed.