如何将BSTR转换为BYTE * [英] How to convert BSTR to BYTE*

查看:80
本文介绍了如何将BSTR转换为BYTE *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个字符串说

BSTR bstrString =Arun;



我有一个字节数组说

BYTE bytArray [5];



那么,如何放置这个BSTR如何使用 ATL 和/或 MFC ,最简单的方法是以下:



 CStringA ansiString(bstrString); 
strncpy(bytArray,ansiString,_countof(bytArray));


你对'place'的意思是什么?

你可以用这种方式复制字符

 BSTR bstrString = SysAllocString(LArun); 
UINT len = SysStringLen(bstrString);
BYTE * bytArray = new BYTE [len];
int i;

for(i = 0; i< len; i ++)
{
bytArray [i] =(BYTE)bstrString [i];
}
// .. $
//不要忘记清理
delete [] bytArray;





但是上面的代码将16位值强制为8位


建议的灵魂很好,但是如果用于中文字符或其他语言的字节数组作为每种语言具有不同的代码点和编码风格来解释字符,则所提出的解决方案不能正常工作。请使用请参阅此页面

[ ^ ]



我的解决方案是使用WideCharToMultiByte适用于所有unicode字符,如chineese或其他人以及英语,因为我们为每种语言都有不同的代码页。在下面的示例中,cp设置为UTF-8编码是用于转换为字节数组的默认标准



BSTR bstr = LArun;



//如果同样的东西用中文写成arun同样有用



BSTR bstr = L阿伦;



int res = WideCharToMultiByte(cp,0,bstr,-1,NULL,0,NULL,NULL);

if(res> 0)

{

BYTE * bytArray = new BYTE [res];



WideCharToMultiByte(cp,0,bstr,-1,& bytArray [0],res,NULL,NULL);

}


Hi,

I have a string say
BSTR bstrString="Arun";

I have a byte Array say
BYTE bytArray[5];

So, how to place this BSTR into BYTE* array?

解决方案

IF you are using ATL and/or MFC the easiest way is the following:

CStringA ansiString(bstrString);
strncpy(bytArray, ansiString, _countof(bytArray));


What do you mean with 'place'?
You may copy the characters this way

BSTR bstrString= SysAllocString(L"Arun");
UINT len = SysStringLen(bstrString);
BYTE * bytArray = new BYTE[len];
int i;

for (i=0; i<len; i++)
{
   bytArray[i] = (BYTE) bstrString[i];
}
//..
// don't forget the cleanup
delete [] bytArray;



However the above code forces 16-bit values into 8 bit ones.


Proposed soultions are good ,however the proposed solutions doesn't work properly if the byte array taken for chinese characters or other languages as each language has different code point and encoding style to interpret the characters .Please refer to this page
[^]

My solution is to use WideCharToMultiByte which works for all the unicode characters like chineese or others as well english as we have different code pages for each language . In below sample ,cp is set as UTF-8 encoding is the default standard used to convert to byte array

BSTR bstr=L"Arun";

// The same works if the same thing is written as arun in chinese

BSTR bstr=L"阿伦";

int res = WideCharToMultiByte(cp, 0, bstr, -1, NULL, 0, NULL, NULL);
if (res > 0)
{
BYTE * bytArray = new BYTE[res ];

WideCharToMultiByte(cp, 0, bstr, -1, &bytArray [0], res, NULL, NULL);
}


这篇关于如何将BSTR转换为BYTE *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆