views:

186

answers:

3

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?

A: 

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.

Douglas Mayle
I retyped only the parts of the function relevant to my question. I made a mistake, it's updated now.
Mr. Smith
+4  A: 

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.

1800 INFORMATION
General idea is right, but SysAllocString() will not perform ANSI-to-Unicode conversion. You'll need to do it yourself: http://stackoverflow.com/questions/606075/how-to-convert-char-to-bstr/606122#606122
sharptooth
Yes, I'm working with actual text, not binary data. Do you mean I should SysAllocString() instead of SysAllocStringByteLen() in this case?
Mr. Smith
Yes, to get a BSTR you need to call either SysAllocString() or SysAllocStringLen() and do the ANSI-to-Unicode conversion as in the linked answer.
sharptooth
I've updated the answer to be correct - that was more or less a think-o - I so rarely work with actual ANSI strings these days
1800 INFORMATION
A: 

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.
}
Igor Zevaka