Function pointer example code

From Second Life Wiki
Jump to navigation Jump to search
class viewer_func  {
       const char * name;
       func_ptr ptr;
       viewer_func() {}
       viewer_func(const char * n, func_ptr p) { name=n; ptr=p;}

class plugin_interface {
       hook * get_hook_by_name(const char *name);
        viewer_func * get_viewer_func_by_name(const char *name);
       LLDynamicArray<hook> hooks;
       LLDynamicArray<viewer_func> viewer_funcs;
       void add_hook(const char *name, const func_ptr ptr);  

      void add_viewer_func(const char *name, func_ptr ptr);
      char ** get_viewer_func_list();
      char ** get_hook_list();
      const char * get_interface_version();
      void * call_viewer_func(const char *name, void *data1, void *data2);
      bool call_hooks(const char *name, void *data1, void *data2);
      void init();

void plugin_interface::add_viewer_func(const char *name, func_ptr ptr) {
       /* This should be called upon instantiation several times, once for
          each internal viewer function we wish to expose to the plugins */
       viewer_funcs.put(*(new viewer_func(name, ptr)));

viewer_func * plugin_interface::get_viewer_func_by_name(const char *name) {
        // this should really be a hash table lookup
       for(int i=0; i < viewer_funcs.count() ; i++) 
               if (!strcasecmp(name, viewer_funcs[i].name)) 
                       return &viewer_funcs[i];
       return NULL;

void * plugin_interface::call_viewer_func(const char *name, void *data1, void *data2) {
        viewer_func * func = get_viewer_func_by_name(name);
        fprintf(stderr, "Calling '%s' @ %p\n", name, func);
        if (func) return (void *)(func->ptr)(data1, data2);
        else return NULL;