String^, const char*, std::string, and c_str( )

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



I am porting Managed C++ code from VS2003 to VS2005. Therefore adopting the
new C++/CLI syntax rather than /clr:oldSyntax.

Much of our managed code is concerned with interfacing to native C++ code
(ie. wrappers etc). In Managed C++ there was an automatic conversion between
const char* and String^. This was useful to us for two reasons:

1. We declared our string constants as eg. const char* const c_My_Constant =
"blah", and these strings could be easily utilised (ie. assigned) to either
a std::string or a String^.
2. We could easily convert/assign std::string to String^ using the .c_str( )
method.

Both of these techniques no longer work in C++/CLI. The implicit conversion
has now disappeared.

Now, in case (2) I have no problem changing all this code to instead use a
"to_string( )" kind of method that converts std::string to String^. It
probably even has the benefit of making the code more readable.

I could obviously do the same thing for case (1) but it irks me to have to
convert a "constant". Unfortunately, however, I have numerous situations
where the same constant will be used by both native and managed C++.

Is there a better way to achieve this?

Thanks

Kevin


.



Relevant Pages

  • Re: Are _T() and TEXT() macros equivalent?
    ... David Ching wrote: ... I would say that the vast majority of the uses of the automatic conversion from narrow to wide string are with hard coded strings where the programmer simply forgot to use _T. ... Soon the ANSI code page will be gone, and hybrid UTF16/UTF8 applications may become more common, and the automatic conversion will do the wrong thing. ...
    (microsoft.public.vc.mfc)
  • Re: getting a form field to default to the value entered in the last record
    ... >concatenating the double quotation marks before and after Me.textbox? ... The DefaultValue property is a string. ... makes the right guess in its automatic conversion process. ...
    (microsoft.public.access.formscoding)
  • Re: getting a form field to default to the value entered in the last record
    ... >concatenating the double quotation marks before and after Me.textbox? ... The DefaultValue property is a string. ... makes the right guess in its automatic conversion process. ...
    (microsoft.public.access.forms)
  • Re: Unicode question
    ... You are right about the null termination being a problem, I usually use the following when interfacing with Win32: ... std::string string; ... are where I employ CString, otherwise I use std::string as much as possible. ...
    (microsoft.public.vc.language)
  • Re: ASCII Conversion
    ... characters, probably not the best choice for interfacing to the CLR, which is ... That is, if you have the string "ABC", the "ASCII ... I need to Take string from this variable with ASCII encoding. ...
    (microsoft.public.vc.mfc)