Training
Module
Perform basic string formatting in C# - Training
Combine literal and variable text data that contain special characters, formatting, and Unicode into meaningful messages for the end user.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
You can convert a String to std::string
or std::wstring
, without using PtrToStringChars
in Vcclr.h.
// convert_system_string.cpp
// compile with: /clr
#include <string>
#include <iostream>
using namespace std;
using namespace System;
void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
void MarshalString ( String ^ s, wstring& os ) {
using namespace Runtime::InteropServices;
const wchar_t* chars =
(const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
int main() {
string a = "test";
wstring b = L"test2";
String ^ c = gcnew String("abcd");
cout << a << endl;
MarshalString(c, a);
c = "efgh";
MarshalString(c, b);
cout << a << endl;
wcout << b << endl;
}
test
abcd
efgh
Training
Module
Perform basic string formatting in C# - Training
Combine literal and variable text data that contain special characters, formatting, and Unicode into meaningful messages for the end user.
Documentation
How to: Convert Standard String to System::String
Learn more about: How to: Convert Standard String to System::String
Learn more about: String (C++/CLI and C++/CX)
How to: Access Characters in a System::String
Learn more about: How to: Access Characters in a System::String