Home > Software engineering >  How to view a System::String with OutputDebugString?
How to view a System::String with OutputDebugString?

Time:06-23

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.

CodePudding user response:

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();

CodePudding user response:

To elaborate on my comment above:

You can use PtrToStringChars to get the string characters you can feed into OutputDebugString.
From the documentation:

PtrToStringChars gives you an interior pointer to the actual String object. If you pass this pointer to an unmanaged function call, you must first pin the pointer to ensure that the object does not move during an asynchronous garbage collection process

Usage example in your case:

#include <vcclr.h>

System::String ^ system_str = gcnew System::String("abcd");
pin_ptr<const wchar_t> wchar_str = PtrToStringChars(system_str);
OutputDebugString(wchar_str);

Note: the pinned pointer wchar_str will be released when it goes out of scope.

  • Related