c++功能函数 字符类型转换

std::string WChar2Ansi(LPCWSTR pwszSrc)
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
	if (nLen <= 0) return std::string("");
	char * pszDst = new char[nLen];
	if (NULL == pszDst) return std::string("");

	WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
	pszDst[nLen - 1] = 0; //为啥不是pszDst [ nLen ] =0 ,有待测试
	std::string strTemp(pszDst);
	delete[] pszDst;
	return strTemp;
}

void Char2Wchar(wchar_t *wc, const char *c, int maxLen)
{
	int len = MultiByteToWideChar(CP_ACP, 0, c, strlen(c), NULL, 0);
	wchar_t * m_wchar = new wchar_t[len + 1];
	MultiByteToWideChar(CP_ACP, 0, c, strlen(c), m_wchar, len);
	m_wchar[len] = '\0';

	if (len >= maxLen)
	{
		delete m_wchar;
		return;
	}

	for (int i = 0; i < len; i++)
	{
		wc[i] = m_wchar[i];
	}

	delete m_wchar;
}

void Wchar2Char(char *c, const wchar_t *wc, int maxLen)//在某程序中运行无效
{
	int len = WideCharToMultiByte(CP_ACP, 0, wc, wcslen(wc), NULL, 0, NULL, NULL);
	char *m_char = new char[len + 1];
	WideCharToMultiByte(CP_ACP, 0, wc, wcslen(wc), m_char, len, NULL, NULL);
	m_char[len] = '\0';

	if (len >= maxLen)
	{
		delete m_char;
		return;
	}

	for (int i = 0; i < len; i++)
	{
		c[i] = m_char[i];
	}

	delete m_char;
}
wchar_t* Char2Wchar_t(const char* szStr)
{
	int nLen = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0);
	if (nLen == 0)
	{
		return NULL;
	}
	wchar_t* pResult = new wchar_t[nLen];
	MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen);
	return pResult;
}
发布了101 篇原创文章 · 获赞 3 · 访问量 6347

猜你喜欢

转载自blog.csdn.net/qq_37631516/article/details/104365914