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.

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a platform independent way to do this?
@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.
Sorry for not accepting your answer directly but I was not at home for a long time and therefore couldn't test it.
@Mythli Hey, no need to apologize. I'm glad it helped out.
0

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

boost::function</*proper function pointer type*/> functionObj = boost::bind(functionPtr); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.