dsollen
dsollen

Reputation: 6459

how to set a default function for a function pointer?

I am loading a function from a .SO 'plugin' file in my code. The plugin will define 3 very specific functions, the full API for each function is defined ahead of time (the point is allow different instances of the same program to modify their behavior via the use of a different plugin. Due to the amount of it's use, need for speed, and my general laziness I decided to use a static function pointer which can store the plugin functions rather then passing the function pointer around various objects.

It's possible for a plugin not to exist, in which case I want to run what is essentially a 'no-op' function in place of the function that would have been read form the plugin. For general safety I want to ensure that the static function pointers point to my no-op functions.

For whatever reason I can't seem to do this. If I try to define the no-op funciton in the .h file and assign my function pointer to it I get all kinds of errors for defining a function in a .h. If I try to declare only the prototype of the method in the .h and assign the function pointer to the prototype I get an undeclared funciton exception, even if the function is defined in a .cpp file.

I know I can easily assign the funciton pointer to a no-op in my main() function. But is there a way to do this so that the .H file gaurentees that the pointer defaults to my no-op function even if I (or someone later) don't properly assign it in my main() method?

Upvotes: 0

Views: 255

Answers (1)

Managu
Managu

Reputation: 9039

Header (say, PluginInterface.h):

extern void (*my_plugin_function_ptr)(...);

Source (say, PluginInterface.cpp):

#include "PluginInterface.h"

static void default_plugin_function(...) {/* does nothing */};

void (*my_plugin_function_ptr)(...)=&default_plugin_function;

Upvotes: 3

Related Questions