UTF8和ANSI互转


std::string Utf8ToAnsi(const char* szUtf8)
{
	bool bNeedFreeW = false;
	int WLength = MultiByteToWideChar(CP_UTF8, 0, szUtf8, -1, NULL, NULL);
	LPWSTR pszW = NULL;
	__try
	{
		pszW = (LPWSTR)_alloca((WLength + 1) * sizeof(WCHAR));
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		pszW = (LPWSTR)malloc((WLength + 1) * sizeof(WCHAR));
		bNeedFreeW = true;
	}
	MultiByteToWideChar(CP_UTF8, 0, szUtf8, -1, pszW, WLength);
	pszW[WLength] = '\0';

	bool bNeedFreeA = false;
	int ALength = WideCharToMultiByte(CP_ACP, 0, pszW, -1, NULL, 0, NULL, NULL);
	LPSTR pszA = NULL;
	__try
	{
		pszA = (LPSTR)_alloca(ALength + 1);
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		pszA = (LPSTR)malloc(ALength + 1);
		bNeedFreeA = true;
	}
	WideCharToMultiByte(CP_ACP, 0, pszW, -1, pszA, ALength, NULL, NULL);
	pszA[ALength] = '\0';

	std::string retStr = pszA;

	if (bNeedFreeW)
	{
		free(pszW);
	}

	if (bNeedFreeA)
	{
		free(pszA);
	}

	return retStr;
}

std::string AnsiToUtf8(const char* szAnsi)
{
	bool bNeedFreeW = false;
	int WLength = MultiByteToWideChar(CP_ACP, 0, szAnsi, -1, NULL, 0);
	LPWSTR pszW = NULL;
	__try
	{
		pszW = (LPWSTR)_alloca((WLength + 1) * sizeof(WCHAR));
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		pszW = (LPWSTR)malloc((WLength + 1) * sizeof(WCHAR));
		bNeedFreeW = true;
	}
	MultiByteToWideChar(CP_ACP, 0, szAnsi, -1, pszW, WLength);

	bool bNeedFreeA = false;
	int ALength = WideCharToMultiByte(CP_UTF8, 0, pszW, -1, NULL, 0, NULL, NULL);
	LPSTR pszA = NULL;
	__try
	{
		pszA = (LPSTR)_alloca(ALength + 1);
	}
	__except (EXCEPTION_EXECUTE_HANDLER)
	{
		pszA = (LPSTR)malloc(ALength + 1);
		bNeedFreeA = true;
	}
	WideCharToMultiByte(CP_UTF8, 0, pszW, -1, pszA, ALength, NULL, NULL);
	pszA[ALength] = '\0';

	std::string retStr(pszA);

	if (bNeedFreeW)
	{
		free(pszW);
	}
	
	if (bNeedFreeA)
	{
		free(pszA);
	}

	return retStr;
}

如果编译报错:

则将 项目 → 属性 → C/C++ → 代码生成 → 启用C++异常,改成“否”

UTF8和ANSI互转_第1张图片

 

你可能感兴趣的:(C++)