How can I use an array of function pointers?

前端 未结 10 1216
别那么骄傲
别那么骄傲 2020-11-22 17:24

How should I use array of function pointers in C?

How can I initialize them?

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 17:43

    Oh, there are tons of example. Just have a look at anything within glib or gtk. You can see the work of function pointers in work there all the way.

    Here e.g the initialization of the gtk_button stuff.

    
    static void
    gtk_button_class_init (GtkButtonClass *klass)
    {
      GObjectClass *gobject_class;
      GtkObjectClass *object_class;
      GtkWidgetClass *widget_class;
      GtkContainerClass *container_class;
    
      gobject_class = G_OBJECT_CLASS (klass);
      object_class = (GtkObjectClass*) klass;
      widget_class = (GtkWidgetClass*) klass;
      container_class = (GtkContainerClass*) klass;
    
      gobject_class->constructor = gtk_button_constructor;
      gobject_class->set_property = gtk_button_set_property;
      gobject_class->get_property = gtk_button_get_property;
    
    

    And in gtkobject.h you find the following declarations:

    
    struct _GtkObjectClass
    {
      GInitiallyUnownedClass parent_class;
    
      /* Non overridable class methods to set and get per class arguments */
      void (*set_arg) (GtkObject *object,
               GtkArg    *arg,
               guint      arg_id);
      void (*get_arg) (GtkObject *object,
               GtkArg    *arg,
               guint      arg_id);
    
      /* Default signal handler for the ::destroy signal, which is
       *  invoked to request that references to the widget be dropped.
       *  If an object class overrides destroy() in order to perform class
       *  specific destruction then it must still invoke its superclass'
       *  implementation of the method after it is finished with its
       *  own cleanup. (See gtk_widget_real_destroy() for an example of
       *  how to do this).
       */
      void (*destroy)  (GtkObject *object);
    };
    

    The (*set_arg) stuff is a pointer to function and this can e.g be assigned another implementation in some derived class.

    Often you see something like this

    struct function_table {
       char *name;
       void (*some_fun)(int arg1, double arg2);
    };
    
    void function1(int  arg1, double arg2)....
    
    
    struct function_table my_table [] = {
        {"function1", function1},
    ...
    

    So you can reach into the table by name and call the "associated" function.

    Or maybe you use a hash table in which you put the function and call it "by name".

    Regards
    Friedrich

提交回复
热议问题