1
votes

how to convert 'String^' to 'const char*'?

     String^ cr = ("netsh wlan set hostednetwork mode=allow ssid=" + this->txtSSID->Text + " key=" + this->txtPASS->Text);
system(cr);

Error :

1   IntelliSense: argument of type "System::String ^" is incompatible with parameter of type "const char *"
2
Copy/paste the title of your question into the Google search box. Lots and lots of hits.Hans Passant
Ok, this one has the good answer, using it as dupe target for many others.Ben Voigt

2 Answers

8
votes

You can do this using the msclr::interop::marshal_context class:

#include <msclr/marshal.h>

Then:

String^ something = "something";

msclr::interop::marshal_context ctx;
const char* converted = ctx.marshal_as<const char*>(something);

system(converted);

The buffer for converted will be freed when ctx goes out of scope.

But in your case it would be much easier to just call an equivalent managed API:

System::Diagnostics::Process::Start("netsh", "the args");
1
votes

The 4 methods on https://support.microsoft.com/en-us/help/311259/how-to-convert-from-system-string-to-char-in-visual-c didn't work for me in VS2015. I followed this advice instead : https://msdn.microsoft.com/en-us/library/d1ae6tz5.aspx and just put it into a function for convenience. I deviated from the suggested solution where it allocates new memory for the char* - I prefer to leave that to the caller, even though this poses an extra risk.

#include <vcclr.h>

using namespace System;

void Str2CharPtr(String ^str, char* chrPtr)
{
   // Pin memory so GC can't move it while native function is called
   pin_ptr<const wchar_t> wchPtr = PtrToStringChars(str);

   // Convert wchar_t* to char*
   size_t  convertedChars = 0;
   size_t  sizeInBytes = ((str->Length + 1) * 2);

   wcstombs_s(&convertedChars, chrPtr, sizeInBytes, wchPtr, sizeInBytes);
}