Expand description
§Purpose
This crate is for producing Rust closures that can cross an FFI boundary. It provides support for any function signature, assuming all of the types in it have valid representations in C/C++ and Rust.
§Safety concerns
Creating a *Closure
by itself can not cause undefined behavior, however when the resulting
structure is used in C/C++ it can still trigger undefined behavior. *Closure
should never be
an argument to a safe function, nor should it be a public member of any structures passed into a safe function.
Please write your own safe wrappers that incorporate the *Closure
types internally.
§Usage in C/C++
To use this with a C/C++ library you’ll need to include the header provided in the repo,
rust_closures.h
. Then you can accept the relevant *Closure
type anywhere that you need to
accept arbitrary Rust code.
§Limitations
This cannot be used to transfer ownership of allocated memory across FFI boundaries, as this crate cannot reasonably guarantee
both sides are using the same memory allocator, or dispose of the types in the same way. If such transfer
is required, you should copy the data into a new allocation, on the side of the FFI boundary it needs to live
on. The major exception to this is types with the Copy
marker trait, which are trivially cloned and require
no disposal instructions.
Functions§
- c_
closure_ header_ include_ dir - Provides the path containing
rust_closures.h
. You’ll need to include this path to compile any C/C++ code making use of this crate’sClosure
types. - enhance_
closure_ bindings - Accepts a blob of auto generated rust code binding to a C/C++ library, probably from
bindgen
, analyzes it searching for instances ofClosure
definitions. When it finds them, it enhances the definition with additional functions that allow passing in a rust closure with a matching signature for theClosure
definition. Outputs the initial blob, with the accompanying enhancements. This attempts torustfmt
the output, but if that fails will instead output rust code on a single line. That can make your error messages really ugly looking.