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

Implement function pointer passing from Rust to C++ #85

Merged
merged 1 commit into from
Mar 30, 2020
Merged

Implement function pointer passing from Rust to C++ #85

merged 1 commit into from
Mar 30, 2020

Conversation

dtolnay
Copy link
Owner

@dtolnay dtolnay commented Mar 30, 2020

For example:

mod ffi {
    extern "C" {
        fn c_take_callback(callback: fn(String) -> usize);
    }
}

This corresponds to an argument of type rust::Fn<> on the C++ side, with an operator() to call the Rust function pointer.

void c_take_callback(rust::Fn<size_t(rust::String)> callback) {
  callback("...");
}

The generated code is currently as follows; we can make this better in subsequent PRs.

void cxxbridge02$c_take_callback(::rust::Fn<size_t(::rust::String)> callback) noexcept {
  void (*c_take_callback$)(::rust::Fn<size_t(::rust::String)>) = c_take_callback;
  c_take_callback$(callback);
}

size_t cxxbridge02$c_take_callback$callback$1(::rust::String *_0, void *) noexcept;

size_t cxxbridge02$c_take_callback$callback$0(::rust::String _0, void *extern$) noexcept {
  return cxxbridge02$c_take_callback$callback$1(&_0, extern$);
}
pub fn c_take_callback(callback: fn(String) -> usize) {
    extern "C" {
        #[link_name = "cxxbridge02$c_take_callback"]
        fn __c_take_callback(callback: ::cxx::private::FatFunction);
    }
    let callback = ::cxx::private::FatFunction {
        trampoline: {
            extern "C" {
                #[link_name = "cxxbridge02$c_take_callback$callback$0"]
                fn trampoline();
            }
            #[export_name = "cxxbridge02$c_take_callback$callback$1"]
            unsafe extern "C" fn __(
                _0: *mut ::cxx::private::RustString,
                __extern: fn(String) -> usize,
            ) -> usize {
                let __fn = "cxx_test_suite::ffi::c_take_callback::callback";
                ::cxx::private::catch_unwind(__fn, move || {
                    __extern(::std::mem::take((*_0).as_mut_string()))
                })
            }
            trampoline as usize as *const ()
        },
        ptr: callback as usize as *const (),
    };
    unsafe { __c_take_callback(callback) }
}

Part of #52.

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

Successfully merging this pull request may close these issues.

None yet

1 participant