Demoting boost::function to a Plain Function Pointer
One of the common challenges faced when dealing with boost::function is the need to convert it into a plain function pointer. This arises when interacting with code expecting a function pointer with a specific signature, while the available function is encapsulated in boost::function.
The Problem
Consider the following code:
typedef void TriggerProc_type(Variable*,void*); void InitVariable(TriggerProc_type *proc); boost::function<void (Variable*, void*)> triggerProc ... InitVariable(triggerProc);
Compilation of this code will result in the following error:
error C2664: 'InitVariable' : cannot convert parameter 1 from 'boost::function<Signature>' to 'void (__cdecl *)(type *,void *)'
The Solution
The suggested solution to this problem lies in creating a shim function that conforms to the expected callback signature:
typedef void (*CallbackType)(int x, void* user_data); void RegisterCallback(CallbackType cb, void* user_data); void MyCallback(int x, void* userData) { boost::function<void(int)> pfn = static_cast<boost::function<void(int)> >(userData); pfn(x); } boost::function<void(int)> fn = boost::bind(myFunction(5)); RegisterCallback(MyCallback, &fn);
In this example, MyCallback serves as the shim function, converting the boost::function into a compatible callback. The user data parameter is utilized to store the boost::function object, allowing MyCallback to access and execute it using a simple cast.
Why Direct Binding is Not Always Feasible
It's important to note that while direct binding of the bound functor is an option, it may not always be suitable. Nontrivial boost::function< > objects typically require multiple pointers, making direct conversion to a C-style callback challenging.
Conclusion
By using a shim function like MyCallback, it becomes possible to effectively bridge the gap between boost::function and C-style callbacks. This approach allows for seamless integration and enables the utilization of boost::function in scenarios where plain function pointers are required.
The above is the detailed content of How to Convert a boost::function to a Plain Function Pointer?. For more information, please follow other related articles on the PHP Chinese website!