In looking into marshal_as one of the function calls expects the following format:
System::String^ const &
What is the purpose of the const & after the managed pointer?
This does not compile for me:
static std::wstring GetString(const System::String^ value)
{
return msclr::interop::marshal_as<std::wstring>(value);
}
Error 1 error C4996:
‘msclr::interop::error_reporting_helper<_To_Type,_From_Type>::marshal_as’: This conversion is not supported by the library or the header file needed for this conversion is not included. Please refer to the documentation on ‘How to: Extend the Marshaling Library’ for adding your own marshaling method. c:\program files (x86)\microsoft visual studio 9.0\vc\include\msclr\marshal.h 203
This does:
static std::wstring GetString(const System::String^ value)
{
return msclr::interop::marshal_as<std::wstring>(const_cast<System::String^>(value));
}
The marshal_as method is defined by this template:
The primary purpose of the extra
const &is to conform to this template declaration.This does affect how the function is called: I checked the IL, and the
String^is passed as a const indirect reference, as one would expect, but that’s not a major change.If the method were standalone, it would probably be declared without the
const &, and there would be little difference.You’re trying to call a method
String^ const &with aString^ const. The compiler can’t make that conversion automatically (safely).What you’re doing with your const_cast is turning the
String^ constinto a regularString^. The compiler can turnString^intoString^ const &safely and automatically.I’d just remove the
constfrom your local method declaration. This compiles for me:Why can’t the compiler make that conversion? Note that
String^ const &andconst String^ const &are not the same thing. The first one says “A constant pointer to a string object”. The second says “A constant pointer to a constant string object“. In your method with(const System::String^ value), you’ve got a constant string object, and the function you’re calling expects a pointer to a non-const string object. We know that the String class is immutable, but the compiler doesn’t, so it won’t pass the address to a const object to a method that thinks the object is non-const.(I’m using Visual Studio 2010 SP1, but I don’t believe the marshal methods had any major changes between 2008 and 2010.)