Converting Managed String to std:string using marshal context

问题描述 投票:0回答:1

我知道帖子:Converting managed System::String to std::string in C++/CLI for the required conversion。但是我遇到了以下使用

marshal_context
的代码。我想了解它是如何工作的。

// required header : #include <msclr/marshal.h>
System::String^ str = gcnew System::String(L"\u0105");
msclr::interop::marshal_context ctx;
auto constChars = ctx.marshal_as<const char*>(str);
std::string myString(constChars);

如果我没记错的话

str
是使用 UTF-16 由 16 位表示的单个“字符”,根据 Unicode 列表 是带有 ogonek 的小拉丁字母
a
。但是
myString
变成了一个单一的字符
?
。这种转换是如何发生的?

此外,为什么在使用 ASCII 字符创建

str
时代码会按“预期”工作,比如
a
。在 UTF-16 中,
a
将以 16 位表示,最多/最少(取决于字节序)有效的 8 位都是
0
。那为什么
myString
只有一个
char
a

c++ string character-encoding c++-cli marshalling
1个回答
1
投票

A

std::string
char
的序列。
char
通常只能包含 ascii 字符(8 位)。当分配一个超过 8 位的 unicode 字符值时,它可能会溢出。当它溢出时,你会得到一个“垃圾”值。

你需要

std::wstring
,它包含一个
wchat_t
序列来表示一个unicode字符串。

因此将最后两行更改为:

//-------------------------------------vvvvvvv--------
auto constChars = ctx.marshal_as<const wchar_t*>(str);

//---vvvvvvv----------------------
std::wstring myString(constChars);
© www.soinside.com 2019 - 2024. All rights reserved.