Flyerenv

03 mai 2006

iconv

Un wrapper c++ pour iconv:


#include
using namespace std;

#include
#include

#define CODAGE_NATIF "ISO-8859-15"
#define CODAGE_XML "UTF-8"

int ppIconv(const std::string &pSource,
const std::string &pFrom_charset,
const std::string &pTo_charset,
std::string &pDestination) {

int retour=0;
char *s = (char *)pSource.c_str();
iconv_t cd = iconv_open(pTo_charset.c_str(), pFrom_charset.c_str());
if (cd != (iconv_t) (-1)) {
size_t s_len = pSource.length();
/* the maximum expansion when converting happens when converting
tscii to utf-8; each tscii char can become up to 4 unicode chars
and each one of those unicode chars can be 3 bytes long */
size_t ptr_len = 4 * 3 * s_len;
//alloca alloue sur la pile, la désallocation se fera
//automatiquement au retour de ppIconv
char *buf = (char *)alloca(ptr_len);
char *ptr = buf;
if ((iconv(cd, &s, &s_len, &ptr, &ptr_len)) != (size_t) (-1)) {
*ptr = 0;
pDestination = buf;
retour=true;
}
iconv_close(cd);
}
if(!retour)
pDestination="";
return retour;
}