Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to mark a C++ type as Trivial? #1332

Closed
metasim opened this issue Mar 29, 2024 · 2 comments
Closed

Is it possible to mark a C++ type as Trivial? #1332

metasim opened this issue Mar 29, 2024 · 2 comments

Comments

@metasim
Copy link

metasim commented Mar 29, 2024

I have a situation where there's a fairly complex C++ enum (below) I wish to be able to return to Rust as Opaque, but by value. IOW, I'd like to mark the type as cxx::kind::Trivial, but don't want a) to duplicate the definition as a shared type, or b) wrap it in a UniquePtr. Is this at all possible with the current cxx?

enum class Type

enum class Type
{
    None = 0,
    Unsigned8 = unsigned(BaseType::Unsigned) | 1,
    Signed8 = unsigned(BaseType::Signed) | 1,
    Unsigned16 = unsigned(BaseType::Unsigned) | 2,
    Signed16 = unsigned(BaseType::Signed) | 2,
    Unsigned32 = unsigned(BaseType::Unsigned) | 4,
    Signed32 = unsigned(BaseType::Signed) | 4,
    Unsigned64 = unsigned(BaseType::Unsigned) | 8,
    Signed64 = unsigned(BaseType::Signed) | 8,
    Float = unsigned(BaseType::Floating) | 4,
    Double = unsigned(BaseType::Floating) | 8
};

@dtolnay
Copy link
Owner

dtolnay commented Mar 29, 2024

Yep, something like this should work:

#[cxx::bridge]
mod ffi {
    unsafe extern "C++" {
        include!("example/include/metasim.h");

        type Type = crate::Type;
        fn metasim() -> Type;
    }
}

#[derive(Debug)]
#[repr(transparent)]
pub struct Type(std::ffi::c_int);

unsafe impl cxx::ExternType for Type {
    type Kind = cxx::kind::Trivial;
    type Id = cxx::type_id!("Type");
}

fn main() {
    println!("{:?}", ffi::metasim());
}

@metasim
Copy link
Author

metasim commented Apr 1, 2024

Wow! Perfect... and simple! Thank you 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants