Skip to content

Commit

Permalink
feat(function_ref): add as_c_callback() member function
Browse files Browse the repository at this point in the history
  • Loading branch information
muggenhor committed Sep 16, 2024
1 parent f1b69a0 commit d335348
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions function_ref.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,19 @@ class function_ref<Signature, R(Args...)>
assert(*this && "*this does not store a callable function target");
return _erased_func(_invocable, std::forward<Args>(args)...);
}

// Helper that exposes the guts of this class to make it easily usable in C-style callbacks.
// This avoids extra indirection & conversion overhead.
// Bit hackis right now, should probably perform some proper conversions to actually rely on defined behavior...
std::pair<void* /* c_cb_arg */, R (*)(void* c_cb_arg, Args...) noexcept(is_noexcept)> as_c_callback() const noexcept {
return {
_invocable.optr,
reinterpret_cast<R (*)(void* c_cb_arg, Args...) noexcept(is_noexcept)>(
// casting via intermediate most basic function pointer to suppress a warning about incompatible function pointer type.
reinterpret_cast<void (*)() noexcept(is_noexcept)>(_erased_func)
),
};
}
};

template <typename R, typename... Args>
Expand Down

0 comments on commit d335348

Please sign in to comment.