char*到LPCWSTR的转换方法

本文探讨了在不同编程环境中处理ANSI和UNICODE字符串时遇到的问题,特别是字符到字符集的转换,提供了从ANSI到UNICODE及反之的解决方法,并通过实例展示了如何在实际代码中应用这些解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学NeHe的Opengl教程,把源代码下了下来,在VC6.0中编译正常,可是拿到VS2005中就各种报错,其实就是一个问题,char*到LPCWSTR的转化问题,也就是ANSI和UNICODE的转换问题,对应那些非变量的字符串,用宏定义_T()就可以解决,比如MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);只要改成MessageBox(NULL,_T("Window Creation Error."),_T("ERROR"),MB_OK|MB_ICONEXCLAMATION);即可,可是悲催的发现有一个函数的形参也存在这种问题,而_T()是解决不了变量的转换的,然后就是各种网上找解放方案,在老外的一个网站上找到了根本解决方法:ANSI到UNICODE的转换:

char *ansistr = "Hello"
int lenA = lstrlenA(ansistr);
int lenW;
BSTR unicodestr;

lenW = ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, 0, 0);
if (lenW > 0)
{
  // Check whether conversion was successful
  unicodestr = ::SysAllocStringLen(0, lenW);
  ::MultiByteToWideChar(CP_ACP, 0, ansistr, lenA, unicodestr, lenW);
}
else
{
  // handle the error
}

// when done, free the BSTR
::SysFreeString(unicodestr);
UNICODE到ANSI的转换:
BSTR unicodestr = 0;
char *ansistr;
SomeCOMFunction(&unicodestr);
int lenW = ::SysStringLen(unicodestr);
int lenA = ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, 0, 0, NULL, NULL);
if (lenA > 0)
{
  ansistr = new char[lenA + 1]; // allocate a final null terminator as well
::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, ansistr, lenA, NULL, NULL);
  ansistr[lenA] = 0; // Set the null terminator yourself
}
else
{
  // handle the error
}

//...use the strings, then free their memory:
delete[] ansistr;
::SysFreeString(unicodestr);
BSTR unicodestr = 0;
char *ansistr;
SomeCOMFunction(&unicodestr);
int lenW = ::SysStringLen(unicodestr);
int lenA = ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, 0, 0, NULL, NULL);
if (lenA > 0)
{
  ansistr = new char[lenA + 1]; // allocate a final null terminator as well
::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, ansistr, lenA, NULL, NULL);
  ansistr[lenA] = 0; // Set the null terminator yourself
}
else
{
  // handle the error
}

//...use the strings, then free their memory:
delete[] ansistr;
::SysFreeString(unicodestr);


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值