System::String to std::string 
Author Message
 System::String to std::string

Just trying my first C++ app with Managed Extensions. So, I decided to try
a function to convert strings. Here's my first attempt:

std::string to_string(System::String *ms)
{
    char ascii_chars __gc[] = System::Text::Encoding::ASCII->GetBytes(ms);
    std::string::size_type nchars = ascii_chars->Length;
    std::string s;
    s.reserve(nchars);
    char const __gc *pc = &ascii_chars[0];
    for (std::string::size_type i=0; i < nchars; i++)
        s += *pc++;
    return s;

Quote:
}

This works, but seems like a lot of steps. Does it look right? Am I
reinventing the wheel?

--
dave



Tue, 21 Sep 2004 04:10:04 GMT  
 System::String to std::string
Here is a better way to do it:

std::string to_string(System::String *ms) {
    std::string s;

    try {
        char *native = static_cast<char *>(
            Marshal::StringToHGlobalAnsi(ms).ToPointer());
        s = native;
        Marshal::FreeHGlobal(native);
    }
    catch (System::Exception *e) {
    }

    return s;

Quote:
}

The Marshal class will take care of pinning down the managed string so that
the garbage collector will not move it behind your back.  It will also take
care of translating between the unicode System::String and your ansi
std::string.  It will throw an exception if there is a problem in the
translation.

I just learned about this an hour ago. :)

-Sean



Tue, 21 Sep 2004 05:23:51 GMT  
 System::String to std::string

Quote:

> The Marshal class will take care of pinning down the managed string so
> that the garbage collector will not move it behind your back.  It will
> also take care of translating between the unicode System::String and
> your ansi std::string.  It will throw an exception if there is a
> problem in the translation.

> I just learned about this an hour ago. :)

Excellent, thanks! Works great.

That InteropServices namespace looks like it has a lot of good stuff in it.
Time to start studying... :-)

--
dave



Tue, 21 Sep 2004 06:19:02 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. System.String to std::string conversion

2. int to std::string to System::String

3. static std::string exposed through System::String *

4. convert non std::string to std::string

5. String to std:string

6. null-terminated string to std::string

7. using std::string and string::npos...

8. Assignind a NULL C string to an std::string

9. convert between std::string and std::wstring

10. Warnings for std::vector<std::string>

11. typedef std::vector<std::string> Vector_String

12. std::hash_map with std::string as a key

 

 
Powered by phpBB® Forum Software