且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C中将BSTR转换为CHAR *并将CHAR *转换为BSTR

更新时间:2022-05-12 05:50:16

您可以使用SysAllocStringStringByteLen()从char *转换为BSTR。但这仅在char *仅包含ASCII字符且不进行任何字符转换的情况下才是安全的。不会引起问题的情况将非常罕见。

You can go from a char* to a BSTR with SysAllocStringByteLen(). But this is only safe if the char* contains only ASCII characters, no character conversion takes place. This not causing problems would be pretty rare.

下一跳是MultiByteToWideChar(),除非您知道该字符串已被另一个编码,否则您通常希望将CodePage参数设置为CP_ACP。办法。产生一个宽字符串,然后您可以将其传递给SysAllocString()以获取BSTR。

Next hop is MultiByteToWideChar(), you typically want to set the CodePage argument to CP_ACP unless you know that the string is encoded another way. That produces a wide string which you can then pass to SysAllocString() to get the BSTR.

另一种方法是WideCharToMultiByte(),除非直接传递BSTR即可,除非它包含嵌入式0个字符。无论如何,转换都是有损失的,要当心,当您使用包含重音符号的字符串或在您使用的代码页中无法表示的任何其他内容时,这可能会引起相当大的麻烦。

The other way around is WideCharToMultiByte(), passing the BSTR directly will work unless it contains embedded 0 chars. The conversion is lossy anyway however, beware the considerable headache this can cause when you work with strings that contain accented characters or anything else that cannot be represented in the code page you use.