上善若水,厚德载物

大道无亲 大象无形 大音希声 大巧若拙 大智若愚 【From small beginnings comes great things.】

 

将托管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 

 
输出结果是:

test
abcd
efgh

 

posted on 2009-05-24 01:53 ChenZB 阅读(2537) 评论(2)  编辑 收藏 引用 所属分类: C++

评论

# re: 将托管C++下的System::String 转换为标准字符串 2009-05-31 18:54 none

很勤奋 向你学习  回复  更多评论   

# re: 将托管C++下的System::String 转换为标准字符串[未登录] 2009-05-31 19:15 chenzb

@none
最近很懒...惭愧惭愧  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿(6)

随笔分类

随笔档案

收藏夹

友情链接

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜