I want to convert WinMain
's cmdLine
argument to argc
and argv
so I can use the argument parsing function I wrote for console applications.
This would be trivial except that I want to support "quotes" too. For example:
test.exe test1 test2 "testi开发者_开发技巧ng testing"
should be
argv[0] = "test.exe"; argv[1] = "test1"; argv[2] = "test2"; argv[3] = "testing testing";
I realize that cmdLine doesn't have the program name (the argv[0]); this doesn't matter I can use a dummy value.
I was thinking of doing it with a regex, (("[^"]+")\s+)|(([^\s]+)\s*)
I'm not sure how well it would work though.. Probably not very well? Is there any function to do that in the windows api? Thanks
If you are using Microsoft compiler, there are public symbols __argc
, __argv
and __wargv
defined in stdlib.h
. This also applies to MinGW that uses Microsoft runtime libraries.
Based on Denis K response
See: https://msdn.microsoft.com/library/dn727674.aspx
This adds Windows specific entrypoint to clasic startpoint of your app:
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char*, int nShowCmd)
{
return main(__argc, __argv);
}
CommandLineToArgvW looks like it would be helpful here.
If you want plain int argc, char** argv arguments you have to do it on your own.
void fetchCmdArgs(int* argc, char*** argv) {
// init results
*argc = 0;
// prepare extraction
char* winCmd = GetCommandLine();
int index = 0;
bool newOption = true;
// use static so converted command line can be
// accessed from outside this function
static vector<char*> argVector;
// walk over the command line and convert it to argv
while(winCmd[index] != 0){
if (winCmd[index] == ' ') {
// terminate option string
winCmd[index] = 0;
newOption = true;
} else {
if(newOption){
argVector.push_back(&winCmd[index]);
(*argc)++;
}
newOption = false;
}
index++;
}
// elements inside the vector are guaranteed to be continous
*argv = &argVector[0];
}
// usage
int APIENTRY WinMain(...) {
int argc = 0;
char** argv;
fetchCmdArgs(&argc, &argv);
}
精彩评论