I really wanted dlsym to be the answer, but I came across the weak attribute for GCC and
#pragma weak
for windows. This is a slightly better match for what I'm trying to do. (bazooka vs fly-swatter situation)
However, I did not know that there was a way to use dlsym on executables, so I will continue reading into that, it would be interesting as a way to implement reflection.
Here's my test for the weak attribute in GCC. I tried to make it cross platform for Windows, but I don't own a windows machine to test it against. Let me know if you test it and it works or not.
Un-comment the "func" function and it will be loaded and run properly, otherwise the function is properly ignored.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <iostream>
#include <unordered_map>
#include <string>
class item
{
public:
item();
void callee();
void (*call)(item *);
};
item::item()
{
call = NULL;
}
void item::callee()
{
std::cout << "Calling member function callee\n";
}
void local(item * owner)
{
std::cout << "Calling local function\n";
owner->callee();
}
#pragma weak func
#ifdef WIN32
void func(item *);
#else
void func(item *) __attribute((weak));
#endif
/*
void func(item * thing)
{
std::cout << "Called fun\n";
if(thing)
{
thing->callee();
}
}
*/
int main()
{
// instructions would be loaded by xml parser
std::string instructions = "onClick";
// reg is managed by smollXML document class
// bobby would technically be a new item pointer populated and returned by doc.getObj(std::string name);
std::unordered_map <std::string, void (*)(item *)> reg;
if(func)
{
std::cout << "Has func\n";
reg["onClick"] = func;
}
else
{
reg["onClick"] = local;
}
item bobby;
bobby.call = reg[instructions];
bobby.call = reg["onClick"];
if(bobby.call)
{
bobby.call(&bobby);
}
}
|
Thank you Mbozzi, you put me on the right path, and you have given me some really good topics to read up on.
That weird part of my brain that likes recursive functions feels like it wants to sink it's teeth into dlsym right now.
[edit: This may not be the true solution, I still have to try it in it's own header which may cause further headaches. If I want this to work then I may have to implement an init() function, but I think this will still be worth the extra work.]