将BSTR转换为BYTE数组C ++

时间:2017-10-14 03:19:01

标签: c++ winapi bstr

我需要从“BSTR”创建“SAFEARRAY of bytes”以将其传递给函数。

我尝试过以下方法从BSTR创建BYTE *。

还有其他方法可以将BSTR转换为BYTE *,这不会导致丢失任何数据吗?

BSTR bstr = SysAllocString(L"This is a basic string which encoded in UTF-16!!ɏ");
int len = WideCharToMultiByte(CP_UTF8, 0, bstr, -1, NULL, 0, NULL, NULL);
BYTE *pByte = new BYTE[len];

if (len > 0)
{
    /*
    for(int i=0; i<len; i++)
    {
        pByte[i] = (BYTE) bstr[i]; //using this way may lead to lose data.
    }
    */
    WideCharToMultiByte(CP_UTF8, 0, bstr, -1, (LPSTR)&pByte[0], len, NULL, NULL);
    //cout << "Byte Array: " << pByte << endl;
}

delete []pByte;

1 个答案:

答案 0 :(得分:1)

SAFEARRAYBSTR都是ActiveX / COM自动化类型。 BSTR是官方字符串类型,那么为什么任何COM / Automation函数都希望将字符串作为SAFEARRAY个字节而不是BSTR?即使这样,也可以使用BSTR而不是SysAllocStringByteLen()通过SAFEARRAY传递原始字节。

现在,要回答您的问题,只需使用SafeArrayCreate()创建字节数组,然后您可以随意填充它。例如:

BSTR bstr = SysAllocString(L"This is a basic string which encoded in UTF-16!!ɏ");
int len = WideCharToMultiByte(CP_UTF8, 0, bstr, -1, NULL, 0, NULL, NULL);
SAFEARRAYBOUND bound;
bound.cElements = len;
bound.lLbound = 0;
SAFEARRAY *sa = SafeArrayCreate(VT_U1, 1, &bound);
if (len > 0) {
    char *data;
    SafeArrayAccessData(sa, (void**)&data);
    WideCharToMultiByte(CP_UTF8, 0, bstr, -1, data, len, NULL, NULL);
    //cout << "Byte Array: " << data << endl;
    SafeArrayUnaccessData(sa);
}
SafeArrayDestroy(sa);
SysFreeString(bstr) ;