GStrv vs. char**

Dear people of the world who are interested in developing with GLib. The type GStrv is a typedef for “char **”. I know C purists will think that it’s stupid to do that. The problem with a “char **” however is that it can mean hundreds of things. That it’s therefore not possible to know for a language binding tool how to deal with it (how get thing things out of it, how to free it and how the content of it will look).

With GStrv all that is known. A language binding generation tool will know that it must use g_strfreev to free it and it will know that your blob of C memory will be an array of strings.

A “char**” can also be a a pointer to the pixbuf of a grayscale image. It can be a binary blob or any kind of array of pointers.

To all our library writers, please do this:

GStrv people_bag_get_names (PeopleBag *people);
GdkPixbuf* people_bag_get_thumbnail_of (PeopleBag *bag, gchar *person);

Don’t do this:

gchar **people_bag_get_names (PeopleBag *people);
gchar **people_bag_get_thumbnail_of (PeopleBag *bag, gchar *person);

Replacing your “gchar**”s with “GStrv”s wont create API nor ABI problems, so please do it now and make a new release of your fixed libraries’s APIs. Then at least the array-of-string glue code of language bindings can be fully automated.

If you are returning an array of object instances, please don’t use GList, GPtrArray nor GHashTable. By using those you loose boxing (your array type is a blob of unknown C memory that contains unknown things that happen to be pointers to GObject instances – but a tool can’t know that -) and (more importantly) you don’t offer a generic collection API for your blob of C memory to other languages.

Consider using a collection API. Some people are trying to get this into GLib just like GIO got accepted as a higher abstraction for a IO and Stream API. Let’s see what happens.

Thanks!

ps. & edit: On IRC jdahlin mentioned that GValueArrays have type information, because the items get boxed onto GValues. If return performance is not an issue, you can also use that instead of GStrv.

5 thoughts on “GStrv vs. char**”

  1. how about start using C++ features instead of reinventing the wheel? Sounds like another instance of NIH to me…

  2. Seems nicer to me to use a special comment that the gobject-introspection scanner would pick up. Gstrv is obfuscated…

  3. This doesn’t seem to convey all the information a language binding would need to know about such a return value: ownership. There are a number of possibilities:

    1. caller owns nothing (i.e. fully constant data)
    2. caller owns the vector but not the contained strings (i.e. const strings)
    3. caller owns both the vector and the strings

    If you made (2) illegal, then I guess “GStrv” vs. “const GStrv” would be enough to handle things.

    For function arguments, it is probably enough to assume that the caller always owns the vector.

Comments are closed.