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

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 ;)

Answers


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);

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


after doing as Yacoby said, almost everything works fine, but when it gets to

link = link + "&passwd=";

it cuts everything what is afterwords in string. when i remove '&' it works just fine... i need the '&' sign


You got the technical solution to your problem but here are a couple other things you might want to consider:

  • Instead of opening a process to do the HTTP request for you, use an API (.NET or C++, in .NET it's much easier than standard C++, look at WebRequest) to do this. Especially if you plan to do something with the response.

  • In general if you're appending to a String multiple times, prefer a StringBuilder. Since String is immutable in .NET, every append requires a new String to be constructed.

  • In this case, don't use a String to build the URL in the first place. Use System::Uri instead.


Need Your Help

How do I make this table using <table>, <tr>, <td> and <div> tags?

css table html html-table

I want to make the following table, but I'm having a bit of difficulty with figuring out which elements to use when. At the moment, this table has been implemented using table tags with the first row

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.