cxx icon indicating copy to clipboard operation
cxx copied to clipboard

Calling Rust async function from C++

Open nasifimtiazohi opened this issue 3 years ago • 4 comments

In the Async Functions chapter, the book shows how to call a C++ async function from Rust. Is there such a workaround in the opposite direction? I'd like my C++ function to call a Rust async function. Something like this:

async fn doThing(arg: Arg) -> Ret {
    Ret {}
}

#[cxx::bridge]
mod ffi {
    unsafe extern Rust {
        fn doThing(Arg arg) -> rust::Future<Ret>;
    }
}
auto ret = co_await doThing();

Following the example in the book, it seems possible if we pass back a function pointer to C++ from Rust that executes rx.await?. However, I see that function pointers with a Result return type are not implemented yet.

Is there any other way we can achieve this? Note that, I'd like creating a channel between Rust and C++ on the Rust side. That is, I'd want to write minimal code on the C++ side to achieve this.

nasifimtiazohi avatar Jul 13 '22 03:07 nasifimtiazohi

@nasifimtiazohi Did you find any workarounds for the time being? I'm also trying to do something similar

casimcdaniels avatar Sep 21 '22 20:09 casimcdaniels

@nasifimtiazohi Did you find any workarounds for the time being? I'm also trying to do something similar

I solved it by using C++ Promise/Future. I sent an opaque C++ Promise type to the Rust side, where I set the promise value through another bridged helper function. On the C++ side, I then waited for the Future to complete.

You might do it using Rust sender/receiver as well. The trick is to not think around passing function pointers. Rather, pass Opaque Rust types/shared types to C++ and execute on those types through some bridged helper functions. It should be doable with more indirections.

nasifimtiazohi avatar Sep 25 '22 04:09 nasifimtiazohi

Hi, any update on direct implementation of this?

Jashwanth537 avatar Jul 10 '23 05:07 Jashwanth537