commit 26d11cdba99a22755472dbeac87303d3ecd47ff2 Author: Steve Myers Date: Thu Jun 3 17:51:07 2021 -0700 First commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..62f41ed --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +*.h +/main +/Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e4d8075 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "bdk_ffi" +version = "0.1.0" +authors = ["Steve Myers "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +crate-type = ["staticlib"] + +[dependencies] +bdk = { version = "^0.7", feature = ["all-keys"] } +safer-ffi = { version = "*", features = ["proc_macros"]} + +[features] +c-headers = ["safer-ffi/headers"] diff --git a/main.c b/main.c new file mode 100644 index 0000000..7321133 --- /dev/null +++ b/main.c @@ -0,0 +1,13 @@ +#include + +#include "bdk_ffi.h" + +int main (int argc, char const * const argv[]) +{ + Point_t * a = new_point(84,45); + Point_t * b = new_point(0.0,39.0); + Point_t * m = mid_point(a, b); + print_point(m); + print_point(NULL); + return EXIT_SUCCESS; +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..6ebf5e7 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,47 @@ +use ::safer_ffi::prelude::*; + +/// A `struct` usable from both Rust and C +#[derive_ReprC] +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct Point { + x: f64, + y: f64, +} + +/* Export a Rust function to the C world. */ +/// Returns the middle point of `[a, b]`. +#[ffi_export] +fn mid_point(a: Option>, b: Option>) -> repr_c::Box { + let a = a.unwrap(); + let b = b.unwrap(); + repr_c::Box::new(Point { + x: (a.x + b.x) / 2., + y: (a.y + b.y) / 2., + }) +} + +/// Pretty-prints a point using Rust's formatting logic. +#[ffi_export] +fn print_point(point: Option>) { + println!("{:?}", point); +} + +#[ffi_export] +fn new_point(x: f64, y: f64) -> repr_c::Box { + repr_c::Box::new(Point { x, y }) +} + +#[ffi_export] +fn free_point(point: Option>) { + drop(point) +} + +/// The following test function is necessary for the header generation. +#[::safer_ffi::cfg_headers] +#[test] +fn generate_headers() -> ::std::io::Result<()> { + ::safer_ffi::headers::builder() + .to_file("bdk_ffi.h")? + .generate() +}