En C++ avec SQLite (et notamment sous Windows avec Win32), il peut arriver que tu doives
convertir des chaînes entre UTF-8 (utilisé par défaut par SQLite) et UTF-16 (utilisé par l’API
Windows). Voici un petit module pragmatique pour faire cette conversion dans les deux sens,
avec des fonctions simples que tu peux appeler directement.
🔁 Module de conversion utf8 <-> utf16
✅ 1. Conversion UTF-8 → UTF-16 (std::wstring)
#include <string>
#include <windows.h>
// UTF-8 -> UTF-16
std::wstring utf8_to_utf16(const std::string& utf8_str) {
int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1,
nullptr, 0);
if (size_needed == 0) return L"";
std::wstring result(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, &result[0],
size_needed);
result.pop_back(); // Remove extra null terminator
return result;
}
✅ 2. Conversion UTF-16 → UTF-8 (std::string)
// UTF-16 -> UTF-8
std::string utf16_to_utf8(const std::wstring& utf16_str) {
int size_needed = WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(), -
1, nullptr, 0, nullptr, nullptr);
if (size_needed == 0) return "";
std::string result(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(), -1, &result[0],
size_needed, nullptr, nullptr);
result.pop_back(); // Remove extra null terminator
return result;
}
📌 Comment utiliser dans ton code ?
// Exemple : convertir un texte saisi par l'utilisateur (LPWSTR) en UTF-8
pour SQLite
std::wstring nom = L";"رشا
std::string nom_utf8 = utf16_to_utf8(nom);
sqlite3_bind_text(stmt, 1, nom_utf8.c_str(), -1, SQLITE_TRANSIENT);
// Exemple : lire depuis SQLite en UTF-8 et afficher dans Win32
const unsigned char* data = sqlite3_column_text(stmt, 1);
std::string utf8_str(reinterpret_cast<const char*>(data));
std::wstring win_str = utf8_to_utf16(utf8_str);
// Utilisable avec MessageBoxW, SetWindowTextW, etc.
🧠 Remarques importantes
MultiByteToWideChar et WideCharToMultiByte sont fournis par Windows
(#include <windows.h>).
Toujours utiliser CP_UTF8 comme code page.
Ces fonctions ajoutent un \0 en fin de chaîne — on l'enlève avec .pop_back() pour
éviter des bugs si tu réutilises la chaîne.
Souhaites-tu que je t’intègre ces fonctions dans un module complet prêt à inclure dans ton
projet Visual Studio ?
Voici un module simple en C++ pour convertir entre UTF-8 et UTF-16 (Unicode utilisé
dans Windows via wchar_t), ainsi qu’un exemple d’appel dans ton application (par exemple,
avec SQLite ou interface graphique Win32).
🔧 1. Module de conversion UTF-8 ↔ UTF-16
#include <windows.h>
#include <string>
// Convertit une chaîne UTF-8 vers UTF-16 (wstring)
std::wstring utf8_to_utf16(const std::string& utf8)
{
if (utf8.empty()) return L"";
int size_needed = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1,
nullptr, 0);
std::wstring wstr(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wstr[0],
size_needed);
wstr.pop_back(); // Supprimer le caractère null final ajouté
automatiquement
return wstr;
}
// Convertit une chaîne UTF-16 (wstring) vers UTF-8
std::string utf16_to_utf8(const std::wstring& utf16)
{
if (utf16.empty()) return "";
int size_needed = WideCharToMultiByte(CP_UTF8, 0, utf16.c_str(), -1,
nullptr, 0, nullptr, nullptr);
std::string str(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, utf16.c_str(), -1, &str[0],
size_needed, nullptr, nullptr);
str.pop_back(); // Supprimer le caractère null final
return str;
}
📌 2. Exemple d'utilisation
🔁 Utilisation pour préparer une requête SQLite (SQLite utilise UTF-8)
std::wstring nomW = L";"رشا
std::string nom_utf8 = utf16_to_utf8(nomW);
// Préparation de la requête
sqlite3_stmt* stmt;
sqlite3_prepare_v2(db, "INSERT INTO utilisateurs(nom) VALUES(?);", -1,
&stmt, nullptr);
// Liaison de paramètre
sqlite3_bind_text(stmt, 1, nom_utf8.c_str(), -1, SQLITE_TRANSIENT);
// Exécution
sqlite3_step(stmt);
sqlite3_finalize(stmt);
🔁 Utilisation pour afficher du texte retourné par SQLite (UTF-8 → UTF-16 pour
interface Win32)
const unsigned char* texte = sqlite3_column_text(stmt, 0);
std::wstring texteW = utf8_to_utf16(reinterpret_cast<const char*>(texte));
// Utiliser avec MessageBox par exemple
MessageBoxW(NULL, texteW.c_str(), L"Contenu récupéré", MB_OK);
✅ Résumé
Conversion Fonction
UTF-8 → UTF-16 utf8_to_utf16(std::string)
UTF-16 → UTF-8 utf16_to_utf8(std::wstring)
Tu peux copier ces fonctions dans un fichier encoding.h/.cpp par exemple, et les utiliser
partout dans ton projet Visual Studio Win32 C++.
Souhaites-tu aussi un exemple complet dans un projet Visual Studio avec cette conversion +
SQLite ?
Le module de conversion UTF-8 ↔ UTF-16 peut fonctionner avec tous les contrôles
Windows à condition de bien comprendre ce qui suit :
🔧 1. Windows utilise UTF-16 (Unicode) en interne
Toutes les API Windows Unicode attendent du texte au format UTF-16LE, représenté
par wchar_t* ou LPCWSTR.
Exemple : SetWindowTextW(HWND, LPCWSTR) ou CreateWindowW(...).
🧰 2. Quand utiliser un module de conversion UTF-8 ↔ UTF-16 ?
✅ Cas d’utilisation :
Lorsque vous recevez du texte UTF-8 (ex : depuis SQLite, fichiers, réseau, etc.) et
vous devez l'afficher dans une interface Windows (ListView, Edit, etc.).
Lorsque vous utilisez des bibliothèques C/C++ (ex : std::string, SQLite) qui
manipulent du UTF-8, et que vous voulez les connecter avec WinAPI qui attend du
UTF-16.
❌ Pas besoin :
Si vous utilisez uniquement des chaînes wstring et fonctions CreateWindowW,
MessageBoxW, SetWindowTextW, etc., tout est déjà en UTF-16, donc pas besoin de
conversion.
🔄 3. Fonctions utiles pour convertir UTF-8 ↔ UTF-16 :
// UTF-8 → UTF-16
std::wstring Utf8ToUtf16(const std::string& utf8) {
int size = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, NULL, 0);
std::wstring utf16(size, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &utf16[0], size);
return utf16;
}
// UTF-16 → UTF-8
std::string Utf16ToUtf8(const std::wstring& utf16) {
int size = WideCharToMultiByte(CP_UTF8, 0, utf16.c_str(), -1, NULL, 0,
NULL, NULL);
std::string utf8(size, 0);
WideCharToMultiByte(CP_UTF8, 0, utf16.c_str(), -1, &utf8[0], size,
NULL, NULL);
return utf8;
}
💡 Exemple pratique :
const unsigned char* utf8_text = sqlite3_column_text(stmt, 1);
std::wstring utf16_text = Utf8ToUtf16((const char*)utf8_text);
SetWindowTextW(hWnd, utf16_text.c_str());
📌 Conclusion :
Oui, le module de conversion fonctionne avec tous les contrôles Windows tant que
tu passes le bon format (UTF-16).
C’est indispensable quand tu reçois des données en UTF-8 et que tu veux les afficher
dans l’interface Win32.
Si tu veux, je peux te donner un petit exemple complet (SQLite → contrôle Edit avec
conversion).