Foreignc
Foreignc is a framework for auto generating a safe ffi abi for rust methods. The main advantage if foreignc is that allows for easy deplayment and maintenance of safe ffi abi. The crate is made up of two parts.
- Macros for auto generating ffi abis and cleanup methods
- Functions for auto generate the recieving end of the ffi abi
- Currently only python is supported
Quick start
Example
# pub use *;
// Create free methods
generate_free_methods!;
// Evaluates to hello_world() -> CResult<()>
The above example will generate a ffi abi, that when called returns a CResult indicating wether the call ended succesfully or not. When arguments are parsed parsed to the function the FromFFi trait is used to convert from a unsafe value into a safe one When values are returned IntoFFi is used, to convert the type into a ffi safe value.
Templating
using the feature 'template' it is possible to auto generate the recieving side of the ffi.
Example
add build = "build.rs"
to the package section of cargo.toml
build.rs
use get_package_dir;
after running cargo build
a api.py file is created that looks like this:
return
return
return
return
return
Then to run using python:
- install foreignc
pip install foreignc
- Use the api
=
=
# Call hello world
=
# prints 0
# prints 1
# BoxedCounter droped when the garbage collector run
Default types
Primititve types
The following primitive types are supported:
- bool
- ()
- i8, i16, i32, i64
- u8, u16, u32, u64
- f32, f64
- &str (will be converted to a CString)
Other types
The following other types are soppurted:
- Result (will be converted to a CResult)
- Option (will be converted to a COption)
- String (will be converted to a CString)
Custom Structs
To parse custom struct accross the ffi barrier use Boxed or Json as such
pub use *;
generate_free_methods!;
pub use ;
// Wil auto generate free method free_boxed_counter
Boxed structs are wrapped in a Box that stores the struct on the heap. Json converts the struct to a string using serde everytime it needs to parse the ffi barrier
Safety
As a rule of thumb, all allocated memory needs too be unallocated by the creator. This is also the basis for generate_free_methods that creates frunctions for freeing memory allocated by structures made by foreignc The following functions are made
- free_string(ptr: *mut CString)
- free_coption(ptr: *mut COption)
- free_cresult(ptr: *mut CResult)
Boxed structs will auto generate a free method using the following convention free_{to_snake_case(struct name)}