Convert std::string to .NET and vice versa.
Can someone post the code so that allows me to take a std::string and turn it into a System::String^ so that i can i use in .NET please.
And the other way around please.
//// clr_utils.h//#pragma once#pragma managed( push, off )#include <string>#pragma managed( pop )//std::string to managed stringSystem::String^ str2mstr( std::string const& source );//managed string to std::stringstd::string mstr2str( System::String^ source );//// clr_utils.cpp//#pragma managed( push, off )#include <vector>#pragma managed( pop )#include "clr_utils.h"#include <vcclr.h>//std::string to managed stringSystem::String^ str2mstr( std::string const& source ){ return gcnew System::String( source.c_str() );}//managed string -> std::stringstd::string mstr2str( System::String^ source ){ //get the string's length, in characters std::size_t str_len = source->Length; std::size_t buffer_len = str_len + 1; //wcstombs_s adds a null terminator std::vector<char> buffer( buffer_len ); std::size_t characters_converted = 0; { pin_ptr<wchar_t const> pwch = PtrToStringChars( source ); wcstombs_s( &characters_converted, &buffer[0], buffer_len, pwch, str_len ); } return std::string( &buffer[0], str_len < characters_converted ? str_len : characters_converted );}
You can use Marshal.PtrToStringAnsi and Marshal.StringToHGlobalAnsi Methods.
Marshal.PtrToStringAnsi
Copies all characters up to the first null from an unmanaged ANSI string to a managed String. Widens each ANSI character to Unicode.
Marshal.StringToHGlobalAnsi
Copies the contents of a managed String into unmanaged memory, converting into ANSI format as it copies.
Marshal.PtrToStringAnsi
Copies all characters up to the first null from an unmanaged ANSI string to a managed String. Widens each ANSI character to Unicode.
Marshal.StringToHGlobalAnsi
Copies the contents of a managed String into unmanaged memory, converting into ANSI format as it copies.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement