Search code examples
visual-studioc++-clioutputdebugstring

How to view a System::String with OutputDebugString?


I am trying to debug a value that is System::String. As I am using Visual Studio, I would normally use OutputDebugString or its variants to see the strings, but System::String aren't natively compatible with OuputDebugString.

How do I convert a System::String to a value that OuputDebugString can print? Or an alternative tool for viewing System::string values?

In case it matters, this is specifically a System::String^ variable.


Solution

  • System::Diagnostics::Trace::WriteLine(L"Your message");
    

    or:

    String^ s = gcnew String(L"Your message");
    System::Diagnostics::Trace::WriteLine(s);
    

    Trace class is internally implemented using OutputDebugString. If you need to use OutputDebugString directly, you can use PtrToStringChars already mentioned in another answer.

    Additional way:

    String^ s = gcnew String(L"Your message\n");
    std::wstring ws = msclr::interop::marshal_as<std::wstring>(s);
    OutputDebugStringW(ws.c_str());