dtolnay / cxx

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

cxx::bridge behind a feature #1325

Open barsdeveloper opened 3 months ago

barsdeveloper commented 3 months ago

I would like to conditionally compile some code only when C++ is also compiled. This is for testing purpose, the tests need some data from the module ffi but not everything inside there, just a few struct.

#[cxx::bridge(namespace = "ao::rust")]
mod ffi {
    pub struct Uuid { // like this one
        pub a: u64,
        pub b: u64,
    }
    #[cfg(feature = "cpp")]
    extern "Rust" {
        // ... not needed, only if compiling c++
    }
}

The problem is when I run the tests from the VS Code UI, It will give an error:

error[E0433]: failed to resolve: use of undeclared crate or module `cxx`
  --> rust_pricing/src/lib.rs:77:3
   |
77 | #[cxx::bridge(namespace = "ao::rust")]
   |   ^^^ use of undeclared crate or module `cxx`

In order t fix the error I put the bridge behind a features like this:

#[cfg_attr(feature = "cpp", cxx::bridge(namespace = "ao::rust"))]
mod ffi {
}

Now running tests from UI works but compiling rust from C++ does not work anymore, I get the error:

[build] error: failed to run custom build command for `rust_pricing v0.1.0 .../ao_rust_sources/rust_pricing)`
[build] 
[build] Caused by:
[build]   process didn't exit successfully: `.../ao_rust_sources/target/release/build/rust_pricing-779c278cdc2546c4/build-script-build` (exit status: 1)
[build]   --- stderr
[build]   cxxbridge: no #[cxx::bridge] module found in src/lib.rs

Apparently it expects exactly #[cxx::bridge(namespace = "ao::rust")], not cfg_attr Is there a way to fix both?

HectorMRC commented 1 month ago

I am facing the same error, it seams that cxx_build does not read the expanded file.