1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//! Generates C bindings for [Interoptopus](https://github.com/ralfbiedert/interoptopus).
//!
//! ## Usage
//!
//! In your library or a support project add this:
//!
//! ```
//! # mod my_crate { use interoptopus::{Library}; pub fn ffi_inventory() -> Library { todo!() } }
//! use my_crate::ffi_inventory;
//!
//! #[test]
//! fn generate_c_bindings() {
//!     use interoptopus::Interop;
//!     use interoptopus_backend_c::{Generator, CWriter, Config};
//!
//!     // Converts an `ffi_inventory()` into Python interop definitions.
//!     Generator::new(Config::default(), ffi_inventory()).write_to("module.h")
//! }
//! ```
//!
//! And we might produce something like this:
//!
//! ```c
//!
//! #ifndef module
//! #define module
//!
//! #ifdef __cplusplus
//! extern "C" {
//! #endif
//!
//! #include <stdint.h>
//! #include <stdbool.h>
//!
//! typedef struct Vec3f32
//! {
//!     float x;
//!     float y;
//!     float z;
//! } Vec3f32;
//!
//! Vec3f32 my_game_function(Vec3f32* input);
//!
//! #ifdef __cplusplus
//! }
//! #endif
//!
//! #endif /* module */
//!
//! ```

use interoptopus::writer::IndentWriter;
use interoptopus::Interop;
use interoptopus::{Error, Library};

mod config;
mod converter;
mod writer;

pub use crate::config::Config;
pub use converter::{CTypeConverter, Converter};
pub use writer::CWriter;

/// **Start here**, main converter implementing [`Interop`].
pub struct Generator {
    config: Config,
    library: Library,
    converter: Converter,
}

impl Generator {
    pub fn new(config: Config, library: Library) -> Self {
        Self {
            config: config.clone(),
            library,
            converter: Converter { config },
        }
    }
}

impl Interop for Generator {
    fn write_to(&self, w: &mut IndentWriter) -> Result<(), Error> {
        self.write_all(w)
    }
}

impl CWriter for Generator {
    fn config(&self) -> &Config {
        &self.config
    }

    fn library(&self) -> &Library {
        &self.library
    }

    fn converter(&self) -> &Converter {
        &self.converter
    }
}