7

私はC++で小さなアプリケーションをプログラムしました。UIにはリストボックスがあります。そして、wstringのみを使用できるアルゴリズムにListBoxの選択されたアイテムを使用したいと思います。

全体として、私には2つの質問があります。

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

wstringテストに?

-コードの^はどういう意味ですか?

どうもありがとう!

4

5 に答える 5

19

それは次のように単純でなければなりません:

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

これを機能させるには、ヘッダーファイルも必要です。

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

好奇心旺盛な人のために、このmarshal_as専門分野は内部でどのように見えるか:

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

これSystem::Stringは、内部でワイド文字として格納されるため機能します。が必要な場合は、std::stringたとえばを使用してUnicode変換を実行する必要がありますWideCharToMultiBytemarshal_asあなたのためにすべての詳細を処理する便利。

于 2012-12-26T23:16:00.923 に答える
0

これを重複としてフラグを付けましたが、からに取得する方法についての回答は次のとおりSystem.String^です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());

秘訣は、マネージコードから非マネージコードへの境界を越える必要があるため、相互運用とマーシャリングを使用することを確認することです。

于 2012-12-26T23:15:23.607 に答える
0

私のバージョンは:

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

std::wstring wstring = str->Data();
于 2014-03-20T00:05:14.267 に答える
0

Visual Studio 2015では、次のようにします。

String^ s = "Bonjour!";

C ++ / CLI

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

C ++ / CX

const wchart_t* ptr = s->Data();
于 2015-12-12T00:15:55.217 に答える
0

マイクロソフトによると:

参照方法:System::Stringを標準文字列に変換する

Vcclr.hでPtrToStringCharsを使用せずに、文字列をstd::stringまたはstd::wstringに変換できます。

// 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;
}

出力:

test
abcd
efgh
于 2021-07-20T21:06:36.867 に答える