2010-02-27 140 views
2

我正在使用Microsoft Visual C++ 2008 我想加入一些字符串,然後在「system」命令中使用它。C++/CLI轉換系統::字符串轉換爲const char *

我試圖做這樣的:

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 

,但我得到錯誤C2664: '系統':無法從 '系統:字符串^' 轉換參數1 '爲const char *'

我很感激任何幫助;)

+0

可能重複的[如何將System :: String轉換爲const char \ *?](http://stackoverflow.com/questions/29335426/how-to-convert-systemstring-to-const-char ) – 2015-03-29 23:51:37

回答

4

看看this questionthis question

實質上,問題在於system函數需要類型爲const char*的變量而不是System::String

因此,您需要將字符串轉換爲一個const char *(使用this answer中的代碼),並將其用作系統函數的參數。

IntPtr p = Marshal::StringToHGlobalAnsi(clistr); 
const char* linkStr = static_cast<char*>(p.ToPointer()); 
system(linkStr); 
Marshal::FreeHGlobal(p); 
+1

一切工作正常,但當它得到︰link = link +「&passwd =」它削減所有後綴字符串 – user4512345632 2010-02-27 15:06:55

+0

忘記調用'元帥:: FreeHGlobal',這會泄漏內存。 – 2010-02-27 16:16:38

+2

這不是異常安全的。使用RAII。微軟已經爲你構建了一個很好的RAII對象,'marshal_context'。 – 2012-04-05 04:14:27

2

要像您一樣使用系統,您需要編組。這需要額外的預防措施,可能導致無法預料的疼痛。

我建議您直接

0

做的Yacoby後表示,通過System::Process class

它與.NET集成好得多,你可以使用System :: string的^調用wget的,幾乎一切工作正常,但當它到達時

link = link + "&passwd="; 

它削減所有字串中的後綴。 當我刪除「&」它工作得很好...我需要的「&」的標誌

0

你得到的技術解決您的問題,但這裏有一些其他的東西,你可能要考慮:

  • 而不是打開一個進程來執行HTTP請求,使用API​​(.NET或C++,在.NET中它比標準C++更容易,請看WebRequest)執行此操作。特別是如果你打算對迴應做些什麼。

  • 一般情況下,如果多次添加String,則優先使用StringBuilder。由於String在.NET中是不可變的,因此每個追加都需要構造一個新的String

  • 在這種情況下,不需要使用String來構建URL。改爲使用System::Uri