char * 、BSTR、long、wchar_t *、LPCWSTR、string、QString、CStringA类型转换
char* 转 BSTR
char* s1 = "zhangsan"; CString s2 = CString(s1); BSTR s3 = s2.AllocSysString();
char* 转 LPCWSTR
char* a = "a.jpg"; WCHAR b[256]; memset(b, 0, sizeof(b)); MultiByteToWideChar(CP_ACP, 0, a, strlen(a) + 1, b, sizeof(b) / sizeof(b[0]));
long 转 char*
// param[0]: long,要转换的数字
// param[1]: char *,转换后指向字符串的指针
// param[2]: 进制
ltoa(age, "age is ", 10);
char* 转 CStringA
char* ch1 = "中文测试123"; CStringA str(ch1);
CStringA 转 char*
CStringA str = L""; char* ch2 = new char[str.GetLength()+1]; memset(ch2, 0, str.GetLength()+1); strcpy(ch2, str.GetString()); delete ch2;
CString 转 BSTR
CString a = "abc"; BSTR b = a.AllocSysString();
wchar_t * 转 char *
wchar_t buffer[MAX_PATH]; BOOL result = SHGetSpecialFolderPath(0, buffer, CSIDL_LOCAL_APPDATA, false); wcscat(buffer, L"\\GPR.log"); int iSize; char* pszMultiByte; //返回接受字符串所需缓冲区的大小,已经包含字符结尾符'\0' iSize = WideCharToMultiByte(CP_ACP, 0, buffer, -1, NULL, 0, NULL, NULL); pszMultiByte = (char*)malloc(iSize * sizeof(char)); WideCharToMultiByte(CP_ACP, 0, buffer, -1, pszMultiByte, iSize, NULL, NULL);
string 转 BSTR
#include <string> #include <comutil.h> #pragma comment(lib, "comsuppw.lib") std::string a = "hello world"; _bstr_t bstr_t(a.c_str()); BSTR res_bstr = bstr_t.GetBSTR();
BSTR 转 string
#include <string> #include <comutil.h> #pragma comment(lib, "comsuppw.lib") BSTR s = L"hello world"; _bstr_t bstr_t(s); std::string str(bstr_t);
QString 转 BSTR
方法一:
QString qstr;
BSTR bstr = SysAllocString((OLECHAR*)qstr.unicode());
方法二:
BSTR str = (BSTR)(LPCWSTR)qstr.data();
QString 转 char*
// 方法一 QString str; char* ch; QByteArray ba = str.toLatin1(); ch = ba.data(); // 方法二 std::string str = QString("zhangsan").toStdString(); const char* ch = str.c_str();
方法三:
QString s1 = "123456"; char* s2 = s1.toLocal8Bit().data();
BSTR 转 QString
方法一:
QString Demo::bstrToqstring(BSTR bstr) { char buf[260] = { 0 }; int len = WideCharToMultiByte(CP_ACP, 0, bstr, wcslen(bstr), NULL, 0, NULL, NULL); WideCharToMultiByte(CP_ACP, 0, bstr, wcslen(bstr), buf, len, NULL, NULL); return QString(buf); }
方法二:
// 获取并显示友好名称 WCHAR *aa = EloamGlobal_GetFriendlyName(1, 0); QString s = QString::fromWCharArray(aa);
方法三:
BSTR data = EloamGlobal_GetBarcodeData(0x02); QString str_InvocrNo = QString::fromStdWString(data);