Reputation: 614
I've got a fairly large MFC application that has just been migrated from VS6.0 to VS2008. It was a pretty painful process, but now I'd like to explore any managed-code options that may be available. I was able to successfully build the project using the /clr switch which seems to give me access to managed types.
I'd like to know if conversion between System::String and CString is automatic or not. The MSDN documentation that I've found suggests that this conversion isn't automatic but I haven't found this to be the case. All three of the examples below work and both 1 and 2 are documented by the MSDN. What I'm curious about is example 3 which also works but I don't know why. The CurrentDirectory property is returning a pointer into the managed heap, String^, but why am I able to assign it to a CString? Exactly what is example 3 doing and what are the memory management implications?
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);
Upvotes: 1
Views: 2115
Reputation: 11589
Option 3 works for pretty much the same reason option 2 does. CString::operator= has an overload for System::String. Don't forget that the assignment operator can do a lot more than copy a reference.
This page: How to: Convert Between Various String Types is very useful for mixed apps. pin_ptr is great.
Be wary of sprinkling managed code around. I also work on a large MFC application that went /clr and I sometimes wish that we had done it in select libraries only. It can make debugging painful when there are a lot of managed-native transitions on the callstack. There are performance considerations as well.
Upvotes: 3
Reputation: 21211
You can go from a system::String to CString because they share a common conversion (lptstr?) going to a System::String from CString will always need System::String^ test = gcnew System::String( CStringVar );
Upvotes: 1