标准字符串std::string和System::String, CString之间的转换

来源:互联网 发布:华夏网络展览馆 编辑:程序博客网 时间:2024/06/05 04:43

1. std::string 转成System.String

#include <string>#include <iostream>using namespace System;using namespace std;int main() {   string str = "test";   cout << str << endl;   String^ str2 = gcnew String(str.c_str());   Console::WriteLine(str2);   // alternatively   String^ str3 = gcnew String(str.c_str());   Console::WriteLine(str3);


2.

#include <string>#include <iostream>using namespace std;using namespace System;using namespace System::Runtime::InteropServices;//System::String转std::stringvoid MarshalString ( String* s, string& os ) {      const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();   os = chars;   Marshal::FreeHGlobal(IntPtr((void*)chars));}//System::String转std::wstringvoid MarshalString ( String* s, wstring& os ) {   const wchar_t* chars = (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();   os = chars;   Marshal::FreeHGlobal(IntPtr((void*)chars));}//System::String转std::stringstring str = "";String* s = "abcdef";const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();str = s;//std::wstringSystem::Stringstring str = "abcdef";String* s;s = new String(str.c_str());//System::String转char*;String* s = "abcdef";char*  ch=  (char*)(void*)Marshal::StringToHGlobalAnsi(s);//System::String转char[];char ch2[100];strcpy(ch2,ch);

 

原创粉丝点击