Pregunta

I programmed a little Application in C++. There is a ListBox in the UI. And I want to use the selected Item of ListBox for an Algorithm where I can use only wstrings.

All in all I have two questions: -how can I convert my

    String^ curItem = listBox2->SelectedItem->ToString();

to a wstring test?

-What means the ^ in the code?

Thanks a lot!

¿Fue útil?

Solución

It should be as simple as:

std::wstring result = msclr::interop::marshal_as<std::wstring>(curItem);

You'll also need header files to make that work:

#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>

What this marshal_as specialization looks like inside, for the curious:

#include <vcclr.h>
pin_ptr<WCHAR> content = PtrToStringChars(curItem);
std::wstring result(content, curItem->Length);

This works because System::String is stored as wide characters internally. If you wanted a std::string, you'd have to perform Unicode conversion with e.g. WideCharToMultiByte. Convenient that marshal_as handles all the details for you.

Otros consejos

I flagged this as a duplicate, but here's the answer on how to get from System.String^ to a std::string.

String^ test = L"I am a .Net string of type System::String";
IntPtr ptrToNativeString = Marshal::StringToHGlobalAnsi(test);
char* nativeString = static_cast<char*>(ptrToNativeString.ToPointer());

The trick is make sure you use Interop and marshalling, because you have to cross the boundary from managed code to non-managed code.

My version is:

Platform::String^ str = L"my text";

std::wstring wstring = str->Data();

With Visual Studio 2015, just do this:

String^ s = "Bonjour!";

C++/CLI

#include <vcclr.h>
pin_ptr<const wchar_t> ptr = PtrToStringChars(s);

C++/CX

const wchart_t* ptr = s->Data();

According to microsoft:

Ref How to: Convert System::String to Standard String

You can convert a String to std::string or std::wstring, without using PtrToStringChars in Vcclr.h.

// convert_system_string.cpp
// compile with: /clr
#include <string>
#include <iostream>
using namespace std;
using namespace System;

void MarshalString ( String ^ s, string& os ) {
   using namespace Runtime::InteropServices;
   const char* chars =
      (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

void MarshalString ( String ^ s, wstring& os ) {
   using namespace Runtime::InteropServices;
   const wchar_t* chars =
      (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
   os = chars;
   Marshal::FreeHGlobal(IntPtr((void*)chars));
}

int main() {
   string a = "test";
   wstring b = L"test2";
   String ^ c = gcnew String("abcd");

   cout << a << endl;
   MarshalString(c, a);
   c = "efgh";
   MarshalString(c, b);
   cout << a << endl;
   wcout << b << endl;
}

output:

test
abcd
efgh
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top