如何将System :: String转换为const char*?

You*_*sef 1 c++-cli

如何将'String ^'转换为'const char*'?

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

错误:

1   IntelliSense: argument of type "System::String ^" is incompatible with parameter of type "const char *"
Run Code Online (Sandbox Code Playgroud)

Luc*_*ski 7

您可以使用以下msclr::interop::marshal_context类来执行此操作:

#include <msclr/marshal.h>
Run Code Online (Sandbox Code Playgroud)

然后:

String^ something = "something";

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

system(converted);
Run Code Online (Sandbox Code Playgroud)

convertedctx超出范围时,将释放缓冲区.

但在您的情况下,调用等效的托管API会更容易:

System::Diagnostics::Process::Start("netsh", "the args");
Run Code Online (Sandbox Code Playgroud)