Share via


System::String -> std::string

Stan has an entry about converting a System::String to an std::string. Wouldn't it be better to minimize the time the string^ is pinned to minimize the effect this code has on the garbage collection process?

bool To_CharStar( String^ source, char*& target )

{

    int len = (( source->Length+1) * 2);

    target = new char[ len ];

    pin_ptr<const wchar_t> wch = PtrToStringChars( source );

    return wcstombs( target, wch, len ) != -1;

}

 

bool To_string( String^ source, string &target )

{

    int len = (( source->Length+1) * 2);

    char *ch = new char[ len ];

    bool result ;

    {

        pin_ptr<const wchar_t> wch = PtrToStringChars( source );

        result = wcstombs( ch, wch, len ) != -1;

    }

    target = ch;

    delete ch;

    return result ;

}