Re: [evolution-patches] Fixes for compiler warnings about signedness



On Fri, 2006-01-06 at 13:33 +0100, Kjartan Maraas wrote:

> I'd like to get some thoughts from others to see how we can get rid of
> these in a sensible manner.

By casting it. You, Kjartan, probably already know this (I don't know).
But I'll put the explanation here for people who don't.

The library methods expect const char pointers because it's a way (for
library developers) to 'promise' that they won't touch the char pointer
(they won't write to it nor alter it).

Of course, using dirty casting tricks, they can still do that. But it's
a form of convention (you can't nor shouldn't attempt to alter const
variables, but it's a pointer . . . so by casting it you can fool the
compiler).

That doesn't mean that you *need* to pass pure const char pointers. Just
tell the compiler that it's okay, that you know what is happening (in
essence, that you trust the library writer).

The case you mention expects a (const xmlChar*) where xmlChar is a
"typedef unsigned char xmlChar". So, a "unsigned const char*" like, for
example, a "string" encapsulated in double quotes.

xmlChar* xmlGetProp (xmlNodePtr node, const xmlChar * name)

If you pass it a normal (char*), it's still okay. The library programmer
just promises you that he's not going to write to it. And you'll have to
eventually deal with the pointer (for example freeing it in case it's an
allocated one).

xmlDocPtr = /* etc */
xmlNodePtr node = /* etc */

gchar *name = g_strdup ("id");
const xmlChar *xatt = (const xmlChar*)name;
xmlChar *xprop = xmlGetProp (node, xatt);
gchar *prop = g_strdup ((const gchar*)xprop);
xmlFree (xprop); /* but don't free xatt */

xmlFreeNode (node);  /* and/or */
xmlFreeDoc (doc); /* etc */

Whether or not the strdup the xprop to prop might or might not be a
necessity. It might depend on how strictly you want to separate GLib
from libxml2. Short version: it doesn't really matter (this way means
introducing an extra string duplication followed by a free of the
original).



-- 
Philip Van Hoof, software developer at x-tend 
home: me at pvanhoof dot be 
gnome: pvanhoof at gnome dot org 
work: vanhoof at x-tend dot be 
http://www.pvanhoof.be - http://www.x-tend.be




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]