2

I'm trying to convert a string to an xmlChar. The compiler says no suitable conversion function from const string to xmlChar exists. This is what the code looks like:

bool ClassName::openFile(const String& ZipFile)
{
    //convert 
    const xmlChar *temp = (const xmlChar)ZipFile; //ZipFile has an error here. ZipFile is path and filename
    ...
}

Any ideas? I googled it and people were converting from xmlChar to string but not this direction.

Christophe
  • 68,716
  • 7
  • 72
  • 138
Michele
  • 3,617
  • 12
  • 47
  • 81
  • 1
    Possibly `const xmlChar *temp = (const xmlChar*)(ZipFile.c_str());` – R Sahu Nov 05 '14 at 19:41
  • 2
    using C style cast with C++ is frowned upon as being poor coding style since it is a source of defects. I suspect you wanted to do something like `const xmlChar *temp = (const xmlChar *)ZipFile.c_str();`? see [how to convert a std::string to const char or char](http://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char) – Richard Chambers Nov 05 '14 at 19:42
  • This is impossible to answer unless you provide the definitions of String and xmlChar, too. – antred Nov 05 '14 at 20:12
  • xmlChar is part of libxml2. Thanks to @Christophe for editing the tags. What R Sahu and Richard Chambers suggested was a great help. I'm all set. Thanks! string is std::string for us. – Michele Nov 05 '14 at 20:26
  • string temp1 = "hello"; const xmlChar *temp = (const xmlChar *)temp1.c_str(); – Michele Nov 05 '14 at 20:27

3 Answers3

3

xmlChar is just a typedef of unsigned char. Just make your sentence like this:

const xmlChar *temp = ZipFile.c_str();
Darien Pardinas
  • 5,910
  • 1
  • 41
  • 48
0

unsafe but removed overhead.

xmlChar *temp = reinterpret_cast<xmlChar*>(ZipFile);

but you must be aware of usage of reinterpret_cast

Rajesh Negi
  • 103
  • 1
  • 8
0

This xml library was written for standard C. There are c style casting methods used at the time that took advantage of the BAD_CAST keyword in the library. Example:

rc = xmlTextWriterWriteElement(writer, BAD_CAST "Value1", BAD_CAST "DATA1");
if (rc < 0) {
    throw EXCEPTION("Error in xmlTextWriterWriteElement");
}

But with c++ if you want to avoid the c-style cast the best you can do is:

rc = xmlTextWriterWriteElement(writer, const_cast<xmlChar*>(reinterpret_cast<const xmlChar *>("Value1")), const_cast<xmlChar*>(reinterpret_cast<const xmlChar *>("DATA1")));

Note that the usual dangers of this casting aren't a problem due to the use case here. We can safely assume the underlying library isn't going to do anything nasty to us.

Devin
  • 31
  • 2