MFC is built using / compiler compiler - CString / System :: String Conversion

I have a fairly large MFC application that has just been migrated from VS6.0 to VS2008. It was quite a painful process, but now I would like to explore any managed code options that may be available. I was able to successfully build the project using the / clr switch, which I think gives me access to managed types.

I would like to know if the conversion between System :: String and CString is automatic or not. The MSDN documentation I found suggests that this conversion is not automatic, but I did not find it to be. All three examples below work and both 1 and 2 are documented on MSDN. I'm curious about example 3, for example, but I don't know why. The CurrentDirectory property returns a pointer to the managed heap String ^, but why can I assign it to CString? Exactly what is example 3 and what are the consequences of memory management?

Example 1)

    marshal_context ^ context = gcnew marshal_context ();
    String ^ env = System :: Environment :: CurrentDirectory;
    const char * env2 = context-> marshal_as (env);
    AfxMessageBox (env2);
    delete context;

Example 2)

    CString s (System :: Environment :: CurrentDirectory);
    AfxMessageBox (s);

Example 3)

    CString s = System :: Environment :: CurrentDirectory;
    AfxMessageBox (s);
+1


source to share


2 answers


Option 3 works for almost the same reason as Option 2. CString :: operator = has an overload for System :: String. Don't forget that the assignment operator can do a lot more than copy a link.

This page: How to Convert Different String Types is very useful for mixed applications. pin_ptr is great.



Be careful when handling managed code. I am also working on a large MFC application that shipped / clr, and I sometimes wish we would only do this in select libraries. This can make debugging painful when there are many managed branches in the callstack. There are performance considerations .

+3


source


You can go from system :: String to CString because they have a common conversion (lptstr?) Going to System :: String from CString will always need System :: String ^ test = gcnew System :: String (CStringVar) ;



+1


source







All Articles