2011-05-30 96 views
1

我發現這非常好的一段代碼,將一個字符串轉換System:String^如:C++/CLI字符串轉換

System::String^ rtn = gcnew String(move.c_str()); // 'move' here is the string 

我傳遞RTN回C#程序。無論如何,在這個代碼存在的函數中,我傳入一個System::String^。我也發現了一些代碼到System:String^轉換爲字符串使用下面的代碼:

pin_ptr<const wchar_t> wch = PtrToStringChars(cmd); // 'cmd' here is the System:String   
size_t convertedChars = 0; 
size_t sizeInBytes = ((cmd->Length + 1) * 2); 
errno_t err = 0; 
char *ch = (char *)malloc(sizeInBytes); 

err = wcstombs_s(&convertedChars,ch, sizeInBytes,wch, sizeInBytes); 

現在我可以用「頻道」作爲一個字符串。

然而,這似乎比使用gcnew轉換其他方式更多的工作。所以,最後我的問題是,有沒有什麼東西可以用gcnew的方式將System::String^轉換爲字符串?

+0

他們讓你做更多的工作,以故意做一些討厭這樣的。至少必須轉換爲utf8,UTF8Encoding :: GetBytes()。 – 2011-05-30 18:28:44

回答

10

使用VC++的編組庫:Overview of Marshaling in C++

#include <msclr/marshal_cppstd.h> 

// given System::String^ mstr 
std::string nstr = msclr::interop::marshal_as<std::string>(mstr); 
+0

聖潔的廢話,多數民衆贊成在甜。謝謝我給它一個。 – David 2011-05-30 18:17:31

+0

工程就像一個魅力。非常感謝。 – David 2011-05-30 18:30:30

+0

如何清理。根據鏈接「Marshaling僅在從託管數據類型到本地數據類型進行編組時才需要上下文,而要轉換爲的本機類型不具有自動清理的析構函數。」 說這個方法是從本地代碼調用的,它會被清理嗎? std :: string getItem(){ String^result =「Some val」; result + =「。」; return msclr :: interop :: marshal_as (result); } – harsha 2013-10-01 11:15:38

0

這可能是有用的:

wchar_t *str = "Hi StackOverflow"; //native 
String^ mstr= Marshal::PtrToStringAnsi((IntPtr)str); // native to safe managed 
wchar_t* A=(wchar_t*)Marshal::StringToHGlobalAnsi(mstr).ToPointer(); // return back to native 

不要忘記using namespace System::Runtime::InteropServices;

+3

由於此方法分配字符串所需的非託管內存,因此請始終通過調用FreeHGlobal釋放內存。 – 2011-06-09 15:56:47