Home > Mobile >  Is there the CommandLineToArgvA function in windows c/c (VS 2022)?
Is there the CommandLineToArgvA function in windows c/c (VS 2022)?

Time:01-05

There is the CommandLineToArgvW() function, which is CommandLineToArgv W, where this W means wide char (wchar_t in C/C ). But the CommandLineToArgvA() function that should exist, such as GetCommandLineW() and GetCommandLineA(), does not exist, apparently.

char:

int argv;
char **argv = CommandLineToArgvA(GetCommandLineA(), &argc);

wide char:

int argv;
wchar_t **wargv = CommandLineToArgvW(GetCommandLineW(), &argc);

Well, I searched every corner of the Internet for the term CommandLineToArgvA() and the most I found was this function in Linux Wine... I want to know, does this function exist, and if yes, is it normal that it is "hidden"? Otherwise, does it really not exist?

edit: The question was whether there was the CommandLineToArgvA function in the Windows API, however, it does not exist (comment by Remy Lebeau). The answer I checked as correct is the one that best explains how to use the existing CommandLineToArgvW function and turn the wchar_t into char, which will provide the same result that would be provided with the CommandLineToArgvA function if it existed.

CodePudding user response:

I don’t think you should try parsing your own command-line string. Windows does it one way. Trying to write duplicate code to do the same thing is the Wrong Thing™ to do.

Just get the command-line, then use the Window facilities to convert it to UTF-8.

#include <stdlib.h>
#include <windows.h>
#include <shellapi.h>

#pragma comment(lib, "Shell32")

void get_command_line_args( int * argc, char *** argv )
{
  // Get the command line arguments as wchar_t strings
  wchar_t ** wargv = CommandLineToArgvW( GetCommandLineW(), argc );
  if (!wargv) { *argc = 0; *argv = NULL; return; }
  
  // Count the number of bytes necessary to store the UTF-8 versions of those strings
  int n = 0;
  for (int i = 0;  i < *argc;  i  )
    n  = WideCharToMultiByte( CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL )   1;
  
  // Allocate the argv[] array   all the UTF-8 strings
  *argv = malloc( (*argc   1) * sizeof(char *)   n );
  if (!*argv) { *argc = 0; return; }
  
  // Convert all wargv[] --> argv[]
  char * arg = (char *)&((*argv)[*argc   1]);
  for (int i = 0;  i < *argc;  i  )
  {
    (*argv)[i] = arg;
    arg  = WideCharToMultiByte( CP_UTF8, 0, wargv[i], -1, arg, n, NULL, NULL )   1;
  }
  (*argv)[*argc] = NULL;
}

Obtains an argv just like the one main() gets, with a final NULL element and writeable and all.

Interface is easy enough. Don’t forget to free() the result when you are done with it. Example usage:

#include <stdio.h>
#include <stdlib.h>

void f(void)
{
  int     argc;
  char ** argv;
  get_command_line_args( &argc, &argv );
  
  for (int n = 0;  n < argc;  n  )
    printf( "  %d : %s\n", n, argv[n] );
  
  free( argv );
}

int main(void)
{
  f();
}

Enjoy!

  • Related