Single header templates for wrapping C++ functors as opaque userdata plus function pointers for C interop.
Features
- Easily wrap functors such as
std::function
or lambdas as function pointers to use in C APIs
- Supports functors with parameters and return values of any type
- Provides deleter functionality to avoid memory leaks, including overloads that return smart pointers
- Requires C++11 or newer
- Automatic arguments / return type deduction when used in C++17
Example usage
typedef void *(*lua_Alloc)(void *ud, void *ptr, size_t osize, size_t nsize);
auto alloc_func = [](void *ptr, size_t osize, size_t nsize) {
ptr = ;
return ptr;
};
void *userdata;
lua_Alloc invoke_fptr;
void (*delete_fptr)(void*);
lua_setallocf(L, invoke_fptr, userdata);
delete_fptr(userdata);
std::tuple< void *, RetType(*)(void *, Args...), void(*)(void *)> prefix_invoker_deleter(Fn &&fn)
Definition functor2c.hpp:108
In case the C API expects the opaque userdata as last argument instead of first, use suffix_invoker_*
functions instead of prefix_invoker_*
.
typedef bool b2CustomFilterFcn(b2ShapeId shapeIdA, b2ShapeId shapeIdB, void* context);
auto filter_callback = [](b2ShapeId shapeIdA, b2ShapeId shapeIdB) {
return true;
};
b2World_SetCustomFilterCallback(world_id, invoke_fptr, userdata.get());
std::tuple< std::unique_ptr< void, typename detail::destroyable_function< false, RetType, Args... >::deleter >, RetType(*)(Args..., void *)> suffix_invoker_unique(Fn &&fn)
Definition functor2c.hpp:226
Integrating with CMake
You can integrate functor2c with CMake targets by adding a copy of this repository and linking with the functor2c
target:
add_subdirectory(path/to/functor2c)
target_link_libraries(my_awesome_target functor2c)