C++ 中的 BSTR 和 SysAllockStringByteLen()

Mr.*_*ith 2 .net c++ string chars visual-studio-2008

我是 C++ 新手,所以这可能是一个菜鸟问题;我有以下功能:

#define SAFECOPYLEN(dest, src, maxlen)                               \
{                                                                    \
    strncpy_s(dest, maxlen, src, _TRUNCATE);                          \
    dest[maxlen-1] = '\0';                                            \
}

short _stdcall CreateCustomer(char* AccountNo)
{
    char tmpAccountNumber[9];
    SAFECOPYLEN(tmpAccountNumber, AccountNo, 9);
    BSTR strAccountNumber = SysAllocStringByteLen(tmpAccountNUmber, 9);

    //Continue with other stuff here.
}
Run Code Online (Sandbox Code Playgroud)

当我通过这段代码进行调试时,例如我传入了帐号“A101683”。当它做SysAllocStringByteLen()部分的时候,账号就变成了中文符号的组合...

任何人都可以对此有所了解?

180*_*ION 6

SysAllocStringByteLen用于创建包含二进制数据而非实际字符串的 BSTR - 不执行 ANSI 到 unicode 转换。这解释了为什么调试器显示字符串包含明显的中文符号,它试图将复制到 BSTR 的 ANSI 字符串解释为 unicode。您可能应该改用SysAllocString -这会将字符串正确转换为 unicode,您必须向它传递一个 unicode 字符串。如果您正在处理实际文本,这就是您应该使用的功能。

  • 总体思路是对的,但 SysAllocString() 不会执行 ANSI 到 Unicode 的转换。你需要自己做:http://stackoverflow.com/questions/606075/how-to-convert-char-to-bstr/606122#606122 (2认同)