Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support passing Rust Fn, FnMut, FnOnce to C++ #668

Open
capickett opened this issue Jan 12, 2021 · 1 comment
Open

Support passing Rust Fn, FnMut, FnOnce to C++ #668

capickett opened this issue Jan 12, 2021 · 1 comment

Comments

@capickett
Copy link
Contributor

capickett commented Jan 12, 2021

Building atop #52, we should be able to support passing Fn, FnMut, FnOnce from rust into C++.

#[cxx::bridge]
mod ffi {
    extern "C++" {
        fn take_fn(arg: u8, callback: Box<dyn Fn(u8)>);
        fn take_fn_mut(arg: u8, callback: Box<dyn FnMut(u8)>);
        fn take_fn_once(arg: u8, callback: Box<dyn FnOnce(u8)>);
    }
}
@capickett
Copy link
Contributor Author

High-level, I think this could be achieved by generating trampolines similar to those used for fn. Another resource I've found discusses a nice trampoline approach: https://adventures.michaelfbryan.com/posts/rust-closures-in-ffi/

The nuance would be in the C++ side, where each type would have a slightly different call operator.

namespace rust {
template <typename R, typename... Args>
class Fn<R(Args...)> {
  // ...
  R operator(Args... args) const noexcept;
};

template <typename R, typename... Args>
class FnMut<R(Args...)> {
  R operator(Args... args) noexcept; // no const
};

template <typename R, typename... Args>
class FnOnce<R(Args...)> {
  R operator(Args... args) && noexcept; // r-value ref qualified
};

Fn seems to be the most straight-forward to implement to me. I think FnOnce could be modeled as above with an r-value ref-qualified call operator that would "null" out its internals after the call. Subsequent calls of rust::FnOnce could then throw an exception similar to std::bad_function_call (https://en.cppreference.com/w/cpp/utility/functional/function/operator()).

I suspect FnMut has some safety issues I'm unaware of. In standard Rust types, we have to Pin the mutable self reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant