將托管C++下的System::String 轉換為標準字符串
今晚在將自動機與.Net下的繪圖工具窗口對接時遇到了C++托管下的string轉化為非托管的標準wstring問題,好在終于在微軟的msdn上找到解決辦法,感覺很好很強大,需收藏下...
1 // convert_system_string.cpp
2 // compile with: /clr
3 #include <string>
4 #include <iostream>
5 using namespace std;
6 using namespace System;
7
8 void MarshalString ( String ^ s, string& os )
9 {
10 using namespace Runtime::InteropServices;
11 const char* chars =
12 (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
13 os = chars;
14 Marshal::FreeHGlobal(IntPtr((void*)chars));
15 }
16 void MarshalString ( String ^ s, wstring& os )
17 {
18 using namespace Runtime::InteropServices;
19 const wchar_t* chars =
20 (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
21 os = chars;
22 Marshal::FreeHGlobal(IntPtr((void*)chars));
23 }
24 int main()
25 {
26 string a = "test";
27 wstring b = L"test2";
28 String ^ c = gcnew String("abcd");
29 cout << a << endl;
30 MarshalString(c, a);
31 c = "efgh";
32 MarshalString(c, b);
33 cout << a << endl;
34 wcout << b << endl;
35 }
36
2 // compile with: /clr
3 #include <string>
4 #include <iostream>
5 using namespace std;
6 using namespace System;
7
8 void MarshalString ( String ^ s, string& os )
9 {
10 using namespace Runtime::InteropServices;
11 const char* chars =
12 (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
13 os = chars;
14 Marshal::FreeHGlobal(IntPtr((void*)chars));
15 }
16 void MarshalString ( String ^ s, wstring& os )
17 {
18 using namespace Runtime::InteropServices;
19 const wchar_t* chars =
20 (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
21 os = chars;
22 Marshal::FreeHGlobal(IntPtr((void*)chars));
23 }
24 int main()
25 {
26 string a = "test";
27 wstring b = L"test2";
28 String ^ c = gcnew String("abcd");
29 cout << a << endl;
30 MarshalString(c, a);
31 c = "efgh";
32 MarshalString(c, b);
33 cout << a << endl;
34 wcout << b << endl;
35 }
36
輸出結果是:
test
abcd
efgh
posted on 2009-05-24 01:53 ChenZB 閱讀(2666) 評論(2) 編輯 收藏 引用 所屬分類: C++