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);
string CBZApiTest::StrToStr(String^ strClr)
{
const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(strClr)).ToPointer();
string str = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
return str;
}
String^ CBZApiTest::clrStrToStr(string str)
{
return gcnew String(str.c_str());
}
2.
#include <string> #include <iostream> using namespace std; using namespace System; using namespace System::Runtime::InteropServices; <span style="color: rgb(255, 0, 0);">//System::String转std::string</span> void MarshalString ( String* s, string& os ) { const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer(); os = chars; Marshal::FreeHGlobal(IntPtr((void*)chars)); } <span style="color: rgb(255, 0, 0);">//System::String转std::wstring</span> void MarshalString ( String* s, wstring& os ) { const wchar_t* chars = (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer(); os = chars; Marshal::FreeHGlobal(IntPtr((void*)chars)); } <span style="color: rgb(255, 0, 0);">//System::String转std::string </span><span style="font-size: 12px;">string str = ""; String* s = "abcdef</span><span style="font-size: 12px;">"; </span>const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer(); str = s; <span style="color: rgb(255, 0, 0);">//std::wstring</span><span style="color: rgb(255, 0, 0);">转</span><span style="color: rgb(255, 0, 0);">System::String</span><span style="font-size: 12px;"> string str = "abcdef"; String* s; s = new String(str.c_str()); </span><span style="color: rgb(255, 0, 0);">//System::String转char*; </span><span style="font-size: 12px;">String* s = "abcdef</span><span style="font-size: 12px;">"; char* ch= (char*)(void*)Marshal::StringToHGlobalAnsi(s); </span><span style="color: rgb(255, 0, 0);">//System::String转char[]; <span style="color: rgb(0, 0, 0);">char ch2[100]; strcpy(ch2,ch);</span></span>