2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MFCのワイド文字とマルチバイト文字を変換する

Last updated at Posted at 2025-11-23

MFCのワイド文字とマルチバイト文字を変換する

MFCの文字列の型はCString型を利用することがほとんどだと思います。しかし、外部のAPIを利用するためにchar*型やstd::string型に変換する必要があったため、その手順を備忘録として記録します。

1 マルチバイト文字とワイド文字とは

マルチバイト文字 ワイド文字
UTF-8 / Shift-JIS など UTF-16 など
CStringA CStringW
std::string std::wstring
char* wchar_t*

詳しくは次のサイトを参考にしてください。

2 前提条件

Visual Studioを次の設定にします。

  • TCHAR型をワイド文字として使用するため、プロジェクトのプロパティにてUnicodeを選択する
  • ワイド文字としてUTF-8を使用するため、プログラムをUTF-8で保存する

image.png

3 プログラム

AppFunction.h
#pragma once

#include "pch.h"

class CAppFunction
{
public:
	CAppFunction();
	virtual ~CAppFunction();

public:
	static char* ConvertStringToChar(const CString& strSrc);
	static CString ConvertCharToString(const char* pCharSrc);
};
AppFunction.cpp

char* CAppFunction::ConvertStringToChar(const CString& strSrc)
{
	// UTF-16 → UTF-8
	int size = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, nullptr, 0, nullptr, nullptr);

	if (size <= 0)
		return false;

	char* pChar = new char[size];

	// UTF-16 → UTF-8
	int res = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, pChar, size, nullptr, nullptr);

	return pChar;
}

CString CAppFunction::ConvertCharToString(const char* pCharSrc)
{
	// UTF-8 → UTF-16
	int size = MultiByteToWideChar(CP_UTF8, 0, pCharSrc, -1, nullptr, 0);

	if (size <= 0)
		return false;

	// UTF-8 → UTF-16
	wchar_t* buffer = new wchar_t[size];
	int res = MultiByteToWideChar(CP_UTF8, 0, pCharSrc, -1, buffer, size);

	CString strRet;

	if (res > 0)
	{
		strRet = CString(buffer);
	}

	delete[] buffer;
	buffer = nullptr;

	return (strRet);
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?