简体   繁体   中英

BSTR and SysAllockStringByteLen() in C++

I'm new to C++, so this may be a noobish question; I have the following function:

#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.
}

When I debug through this code, I pass in the account number "A101683" for example. When it does the SysAllocStringByteLen() part, the account number becomes a combination of Chinese symbols...

Anyone that can shed some light on this?

SysAllocStringByteLen is meant for when you are creating a BSTR containing binary data, not actual strings - no ANSI to unicode conversion is performed. This explains why the debugger shows the string as containing apparently chinese symbols, it is trying to interpret the ANSI string copied into the BSTR as unicode. You should probably use SysAllocString instead - this will convert the string correctly to unicode you must pass it a unicode string. If you are working with actual text, this is the function you should be using.

First of all, there's a problem with the line containing SAFECOPYLEN. It's missing ')' and it's not clear what it's supposed to do.

The second issue is that you're not using AccountNo anywhere in this code. tmpAccountNumber is on the stack, and could have anything in it.

BSTR are double-byte character arrays so you can't just copy a char* array into it. Instead of passing it "A12123" try L"A12323" .

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

//Continue with other stuff here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM