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 w开发者_Go百科ith "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 ;)
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 aStringBuilder
. SinceString
is immutable in .NET, every append requires a newString
to be constructed.In this case, don't use a
String
to build the URL in the first place. Use System::Uri instead.
精彩评论