C++/CLI Converting System::String to const char*

10,746

Solution 1

Take a look at this question and this question.

In essence, the problem is that the system function expects a variable of the type const char* rather than System::String.

So you need to convert the string to a const char* (Using code from this answer) and use that as an argument for the system function.

IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
const char* linkStr = static_cast<char*>(p.ToPointer());
system(linkStr);
Marshal::FreeHGlobal(p);

Solution 2

To use system as you do, you will need Marshalling. This requires extra precautions which can lead to unforeseen pain.

I recommend that you call wget via the System::Process class

It integrates with .NET much better and you can use System::String^ directly

Share:
10,746
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm using Microsoft Visual C++ 2008 I want to join some strings, and then use it with "system" command.

    I tried to do it like this:

    System::String^ link;
    link = "wget.exe --output-document=log http://ADDRESS";
    link = link + System::String::Copy(textBox_login->Text);
    link = link + "&passwd=";
    link = link + System::String::Copy(textBox_passwd->Text);
    system(link); //LINE WITH ERROR
    

    But i get error C2664: 'system' : cannot convert parameter 1 from 'System::String ^' to 'const char *'

    I appreciate any help ;)