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*

复制代码
// 方法一
QByteArray ba = QString("123456").toLatin1();
char* ch = ba.data();

// 方法二
const char* ch = QString("zhangsan").toStdString().c_str();

// 方法三(推荐,支持中文)
char* ch = QString("12345678哈哈").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);

 

posted @   十一的杂文录  阅读(394)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示