今晚在将自动机与.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
输出结果是:
test
abcd
efgh