2015-10-07 190 views
0

是否有一種簡單的方法(一行代碼很酷)將àstd :: string轉換爲C++/CX中的Platform :: String^?C++/CX:將std :: string轉換爲Platform :: String^

我找到了how to do it the other way(字符串^到字符串),但沒有爲這一個。

喜歡的東西:

std::string str = "Hello World"; 
Platform::String^ p_str = convertFromString(str); 

(在這是毫無意義的,但比如當你用的std ::在C++字符串的情況下想將它發送到一些C#代碼,它更有意義)

+0

你總是可以嘗試使用一個charArray它們之間的轉換? – Cjen1

+2

感嘆,22年的Unicode並不能阻止這樣的問題。您已經知道如何從該帖子轉換爲std :: wstring。然後它是一個單線程,ref新的字符串(wide.c_str()) –

+0

我可以做其他工具(用char *等等......),但我想知道是否有一個好/簡單的方法它 – ashtrail

回答

-1

所以基本上答案是否定的:它更復雜。你需要先在std :: wstring中轉換std :: string,然後使用user1的回答(將std :: wstring轉換爲Platform :: String ^)。 對於字符串到wstring的轉換,你可以檢查this other question(這不適用於我,但無論如何,我只需要進行更深入的轉換)。

(我已經放了一些代碼,但被告知這樣做很糟糕,因爲我只是爲了調試而做,而且無論如何都將其刪除,我不在乎,但我不想提供反建議所以我刪除了該代碼)

+0

好^^如果你這麼說 – ashtrail

0

目前沒有直接std::stringstd::wstring的轉換可能。

然而,我們可以做一個迂迴的轉換,從std::stringstd::wstring,然後從std::wstringPlatform::String如下:

#include <locale> 
#include <codecvt> 
#include <string> 

Platform::String^ stringToPlatformString(std::string inputString) { 
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; 
    std::wstring intermediateForm = converter.from_bytes(inputString); 
    Platform::String^ retVal = ref new Platform::String(intermediateForm.c_str()); 

    return retVal; 
} 

std::stringstd::wstring轉換的更多信息,請參見this question

0

的方法對我的作品

Platform::String^convertFromString(const std::string & input) 
{ 
    std::wstring w_str = std::wstring(input.begin(), input.end()); 
    const wchar_t* w_chars = w_str.c_str(); 

    return (ref new Platform::String(w_chars)); 
} 
+0

工作對我來說略有改變返回'返回(ref new Platform :: String(w_chars,w_str.length()));' – miradham

相關問題