如何正确使用 WideCharToMultiByte
我已阅读 WideCharToMultiByte 上的文档,但是我被这个参数困住了:
lpMultiByteStr
[out] Pointer to a buffer that receives the converted string.
我不太确定如何正确初始化变量并将其输入函数中
I've read the documentation on WideCharToMultiByte, but I'm stuck on this parameter:
lpMultiByteStr
[out] Pointer to a buffer that receives the converted string.
I'm not quite sure how to properly initialize the variable and feed it into the function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这里有几个函数(基于 Brian Bondy 的示例),它们使用 WideCharToMultiByte 和 MultiByteToWideChar 使用 utf8 在 std::wstring 和 std::string 之间进行转换,以免丢失任何数据。
Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.
详细阐述 Brian R. Bondy 提供的答案:以下示例说明了为什么不能简单地调整输出缓冲区的大小源字符串中的宽字符数:
输出:
Elaborating on the answer provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:
And the output:
您可以通过创建新的字符数组来使用 lpMultiByteStr [out] 参数。 然后传入这个 char 数组来填充它。 只需要初始化字符串的长度+1,这样转换后就可以得到一个以null结尾的字符串。
这里有一些对您有用的辅助函数,它们显示了所有参数的用法。
--
任何时候在文档中,当您看到它有一个指向类型的指针的参数,并且他们告诉您这是一个输出变量时,您将需要创建该类型,然后传入指向它的指针。 该函数将使用该指针来填充您的变量。
所以你可以更好地理解这一点:
You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.
So you can understand this better:
以下是
WideCharToMultiByte
和MultiByteToWideChar
的C
实现。在这两种情况下,我都会确保将
null
字符附加到目标缓冲区的末尾。和
即使有人指定
-1
并传入以null
结尾的字符串,我仍然为额外的null
字符分配足够的空间,因为对于我的用例来说,这不是问题。Here is a
C
implementation of bothWideCharToMultiByte
andMultiByteToWideChar
.In both cases I ensure to tack a
null
character to the end of the destination buffers.And
Even if someone specifies
-1
and passes in anull
terminated string I still allocate enough space for an additionalnull
character because for my use case this was not an issue.我正在使用这两个辅助函数:
我认为这是封装这两个函数的最通用的方法。 使用这些API变得更加方便。
I'm using this two helper-functions:
I think this is the most versatile way to encapsulate both functions. Using these APIs becomes more convenient.