简体   繁体   中英

pyo3 optionally generate python bindings for rust struct

I have defined a few structs in my code and if a certain feature is enabled on the crate, I would like to generate Python bindings for those structs as well. Right now I am not able to get it correctly. Let's say I have a struct MyStruct for which I want to optionally generate Python Bindings.

I have tried something like the following

cfg_if! {
    if #[cfg(feature = "python-bindings")] {
        #[pyclass]
    } 
    else {
    }  
}
struct MyStruct{
   value: i32
}

I would like to only add #[pyclass] if feature python-bindings is enabled and not otherwise.

This works fine if python-bindings is not enabled. But if I compile with --features python-bindings , I get the following error.

error: expected item after attributes

As far as possible I do not want to duplicate the code. like

cfg_if! {
    if #[cfg(feature = "python-bindings")] {
        #[pyclass]
        struct MyStruct{
           value: i32
        }
    } 
    else {
        struct MyStruct{
            value: i32
        }
    }  
}

Is there a way of doing it without duplicating the code?

Yes, with #[cfg_attr] :

#[cfg_attr(feature = "python-bindings", pyclass)]
struct MyStruct {
    value: i32
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM