• Advertisement
Sign in to follow this  

Convert std::string to .NET and vice versa.

This topic is 4038 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
Advertisement

//
// clr_utils.h
//

#pragma once

#pragma managed( push, off )
#include <string>
#pragma managed( pop )


//std::string to managed string
System::String^ str2mstr( std::string const& source );

//managed string to std::string
std::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 string
System::String^ str2mstr( std::string const& source )
{
return gcnew System::String( source.c_str() );
}

//managed string -> std::string
std::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 );
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement