私はC++で小さなアプリケーションをプログラムしました。UIにはリストボックスがあります。そして、wstringのみを使用できるアルゴリズムにListBoxの選択されたアイテムを使用したいと思います。
全体として、私には2つの質問があります。
String^ curItem = listBox2->SelectedItem->ToString();
wstringテストに?
-コードの^はどういう意味ですか?
どうもありがとう!
私はC++で小さなアプリケーションをプログラムしました。UIにはリストボックスがあります。そして、wstringのみを使用できるアルゴリズムにListBoxの選択されたアイテムを使用したいと思います。
全体として、私には2つの質問があります。
String^ curItem = listBox2->SelectedItem->ToString();
wstringテストに?
-コードの^はどういう意味ですか?
どうもありがとう!
それは次のように単純でなければなりません:
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変換を実行する必要がありますWideCharToMultiByte
。marshal_as
あなたのためにすべての詳細を処理する便利。
これを重複としてフラグを付けましたが、からに取得する方法についての回答は次のとおり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());
秘訣は、マネージコードから非マネージコードへの境界を越える必要があるため、相互運用とマーシャリングを使用することを確認することです。
私のバージョンは:
Platform::String^ str = L"my text";
std::wstring wstring = str->Data();
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();
マイクロソフトによると:
参照方法: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