Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将BSTR转换为字节数组C++;_C++_Winapi_Bstr - Fatal编程技术网

C++ 将BSTR转换为字节数组C++;

C++ 将BSTR转换为字节数组C++;,c++,winapi,bstr,C++,Winapi,Bstr,我需要从“BSTR”创建一个“安全字节数组”,将其传递给函数 我尝试了以下方法从BSTR创建字节* 是否有其他方法将BSTR转换为不会导致任何数据丢失的字节*? 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 =

我需要从“BSTR”创建一个“安全字节数组”,将其传递给函数

我尝试了以下方法从BSTR创建字节*

是否有其他方法将BSTR转换为不会导致任何数据丢失的字节*?

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;
BSTR BSTR=SysAllocString(L“这是一个用UTF-16编码的基本字符串!!ɏ”);
int len=WideCharToMultiByte(CP_UTF8,0,bstr,-1,NULL,0,NULL,NULL);
字节*pByte=新字节[len];
如果(len>0)
{
/*

对于(int i=0;i
SAFEARRAY
BSTR
都是ActiveX/COM自动化类型。
BSTR
是正式的字符串类型,那么为什么任何COM/automation函数都希望将字符串作为字节的
SAFEARRAY
而不是
BSTR
?即使如此,也可以通过
BSTR
usi传递原始字节ng
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) ;
BSTR BSTR=SysAllocString(L“这是一个用UTF-16编码的基本字符串!!ɏ”);
int len=WideCharToMultiByte(CP_UTF8,0,bstr,-1,NULL,0,NULL,NULL);
安全绑定;
绑定。cElements=len;
bound.lLbound=0;
SAFEARRAY*sa=SafeArrayCreate(VT_U1、1和绑定);
如果(len>0){
字符*数据;
安全阵列访问数据(sa,(作废**)和数据);
宽图表多字节(CP_UTF8,0,bstr,-1,数据,len,NULL,NULL);

//第二个
WideCharToMultiByte
调用有什么不起作用呢?一个完整、具体的失败示例会很有帮助。你的代码与此无关。
BSTR
是安全的。我猜你只是想将UTF-16转换为UTF-8。错误的Unicode转换可能会导致数据丢失。你不需要
BSTR用于此。请在
SysAllocString
之后将
SysFreeString
放入清理。