1

How can I initialize a boost::function object with a raw function pointer?

Metacode

extern "C"
{
    class Library
    {
        ...
    };
    Library* createLibrary();
}

...

void* functionPtr = library.GetFunction("createLibrary");
boost::function<Library*()> functionObj(functionPtr);

Library* libInstance = functionObj();

If you need additional information's just let me know.

Mythli
  • 5,995
  • 2
  • 24
  • 31

2 Answers2

1

void* is not a function pointer, so you can't create a boost::function from it. You probably want to convert this to a proper function pointer first. How to do that is implementation dependent.

This is how this ugly conversion is recommended in POSIX (rationale):

void* ptr = /* get it from somewhere */;
Library* (*realFunctionPointer)(); // declare a function pointer variable
*(void **) (&realFunctionPointer) = ptr // hack a void* into that variable

Your platform may require different shenanigans.

Once you have such a pointer you can simply do:

boost::function<Library*()> functionObj(realFunctionPtr);

Library* libInstance = functionObj();
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • Is there a platform independent way to do this? – Mythli Dec 02 '11 at 15:53
  • @Mythli: No. Like I said, converting a `void*` to a function pointer is platform dependent. If you have access to a real function pointer inside `GetFunction`, you may be able to refactor it into templates and avoid `void*`, and thus skip all the platform-specific nasties. – R. Martinho Fernandes Dec 02 '11 at 15:55
  • Sorry for not accepting your answer directly but I was not at home for a long time and therefore couldn't test it. – Mythli Dec 08 '11 at 13:43
  • @Mythli Hey, no need to apologize. I'm glad it helped out. – R. Martinho Fernandes Dec 08 '11 at 14:01
0

with boost::bind you can literly bind functions to a boost function object.

boost::function</*proper function pointer type*/> functionObj = boost::bind(functionPtr); 
Michael Haidl
  • 5,384
  • 25
  • 43