gpt4 book ai didi

c++ - 哪个是在 C/C++ 中将 BSTR 参数转换为 ANSI 的更好代码?

转载 作者:太空狗 更新时间:2023-10-29 19:45:11 24 4
gpt4 key购买 nike

到目前为止,我发现我可以通过两种(很多?)方式将传入的 BSTR 转换为 ANSI,我很想知道在速度/效率等方面,一种是否比另一种“更好”。

我使用了一段时间的方法是使用 USES_CONVERSIONW2A 宏,例如

BSTR __stdcall F(BSTR p1, BSTR p2 ) {
USES_CONVERSION;

LPSTR sNum1 = W2A( p1 );
LPSTR sNum2 = W2A( p2 );

然而,最近我遇到了另一种技术:

BSTR __stdcall F(BSTR p1, BSTR p2 ) {
long amt = wcstombs( NULL, p1, 1 );
sNum1 = (char *) malloc( amt );
wcstombs( sNum1, p1, amt );
*(sNum1 + amt) = '\0';

amt = wcstombs( NULL, p2, 1 );
sNum2 = (char *) malloc( amt );
wcstombs( sNum2, p2, amt );
*(sNum2 + amt) = '\0';

现在我承认,它更冗长,并且有两次调用 wcstombs 但据我所知,USES_CONVERSIONW2A 宏可能是隐藏各种乐趣和游戏。

哪个是更高效/更快的代码?或者,我可以使用另一种技术来更好地完成这项工作吗?

最佳答案

来自 MSDN :

[...]The recommended way of converting to and from BSTR strings is to use the CComBSTR class. To convert to a BSTR, pass the existing string to the constructor of CComBSTR. To convert from a BSTR, use COLE2[C]DestinationType[EX], such as COLE2T.

来自 CComBSTR 页面:

[...]The CComBSTR class provides a number of members (constructors, assignment operators, and comparison operators) that take either ANSI or Unicode strings as arguments. The ANSI versions of these functions are less efficient than their Unicode counterparts because temporary Unicode strings are often created internally. For efficiency, use the Unicode versions where possible.

关于c++ - 哪个是在 C/C++ 中将 BSTR 参数转换为 ANSI 的更好代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/576610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com