dtolnay / cxx

Safe interop between Rust and C++
https://cxx.rs
Apache License 2.0
5.89k stars 336 forks source link

Submodules inside ffi definition #928

Open TheZoq2 opened 3 years ago

TheZoq2 commented 3 years ago

As my project grows, the ffi namespace is becoming quite bloated and hard to navigate around, therefore, it would be nice if it was possible to support adding mod to the ffi functions on the rust side, something like

    unsafe extern "C++" {
        include!("cinnabar/cinnabar_src/ffi/ffi.hpp");

        type RcNode;

        fn wrap_rc(to_wrap: &RcNode) -> UniquePtr<RcNode>;

        // Node constructor wrappers
        mod nodes {
            fn new_config(word_length: i32, single_node_interp: bool) -> UniquePtr<Config>;

            fn frac_const(val: f64) -> UniquePtr<RcNode>;
            fn bool_const(val: bool) -> UniquePtr<RcNode>;
            fn new_input(name: &str, min: f64, max: f64, val: f64) -> UniquePtr<RcNode>;
            fn new_non_referenced(name: &str, description: &str, parents: &[UniquePtr<RcNode>]) -> Result<UniquePtr<RcNode>>;

            // ..
        }

        mod opt_passes {
            // Opt passes
            fn constant_fold() -> UniquePtr<OptPass>;
            fn remove_redundant_comparisons() -> UniquePtr<OptPass>;
            fn remove_redundant_interp_validity() -> UniquePtr<OptPass>;
            fn remove_redundant_bool_computations() -> UniquePtr<OptPass>;
            fn constant_division_replacement() -> UniquePtr<OptPass>;
            fn merge_bools() -> UniquePtr<OptPass>;
            fn select_else_last() -> UniquePtr<OptPass>;
            fn select_else_x() -> UniquePtr<OptPass>;
            fn remove_single_select() -> UniquePtr<OptPass>;
        }
    }

As far as I can tell, this isn't possible, I get a compiler error when I try, but I might also be missing something

If it's something desired and not too difficult to implement, I wouldn't mind giving it a shot if you can give me some pointers for where to look.

And of course, thanks for making this amazing library, being able to incrementally migrate my work project to rust has been a huge improvement for me!

mattiekat commented 3 years ago

Our of curiosity, have you tried using multiple bridge modules? It does require a little more config but it would accomplish a similar thing. You can also pub use ffi::* so that it is almost like the module is native rust.

If you are not aware reusing existing binding types and the bridges fn might be helpful.