how to convert System::String to const char*?

匆匆过客 提交于 2019-11-26 08:38:33

问题


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 *\"

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/29335426/how-to-convert-systemstring-to-const-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!