Home >Backend Development >C++ >How to Safely Pass a `boost::function` to a Plain Function Pointer?
Demoting Boost::function to a Plain Function Pointer
Problem:
Passing a boost::function as a plain function pointer with the same signature to a method that requires one can result in errors, such as C2664.
Resolution:
While some answers suggest using target() to retrieve a pointer from a boost::function, this only works for trivial cases where the initially bound object was eligible for binding to a C callback.
For non-trivial cases, the underlying mechanism of a boost::function necessitates multiple pointers, not just one. Therefore, a more robust solution is to create a shim function that conforms to the callback signature and delegates the call to the boost::function stored as user data.
Example:
// Shim function for callback typedef void (*CallbackType)(int x, void* user_data); void MyCallback(int x, void* userData) { boost::function<void(int)>& pfn = static_cast<boost::function<void(int)> &>(userData); pfn(x); } // Usage boost::function<void(int)> fn = boost::bind(myFunction(5)); RegisterCallback(MyCallback, &fn);
This approach enables the use of boost::function with C callbacks that include user data. However, if the callback signature lacks a user data pointer, it may require a complete redesign to become usable under most circumstances.
The above is the detailed content of How to Safely Pass a `boost::function` to a Plain Function Pointer?. For more information, please follow other related articles on the PHP Chinese website!