Search code examples
cglibgobject

How to call a function by name using GObject?


That function I want to call using GObject does look like the following:

char * some_object_fun(SomeObject *self, char *input);

Is there a good way to achieve this? I would be very interested in an elegant solution.


Solution

  • C doesn't really support introspection/reflection like you may be used to if you're coming from something like Python, PHP, Java, etc.

    I don't know that I'd call it "elegant", but most operating systems offer a way to get the address of a public symbol, so if your symbol is public you can use that, cast it to a function pointer of the appropriate type, then invoke the function. On POSIX, the relevant functions are called dlopen and dlsym. On Windows, LoadLibrary and GetProcAddress.

    Your tags mention GObject, so that simplifies things a bit; you can just use g_module_open and g_module_symbol (which are basically abstractions over the functions I mentioned above).

    The code would look something like:

    char* (* sym)(SomeObject*, char*);
    GModule* module = g_module_open(NULL, 0);
    sym = g_module_symbol("some_object_fun");
    sym(instance, input);
    g_module_close(module);
    

    Plus some error handling, of course, but you should be able to figure that part out.