cxx icon indicating copy to clipboard operation
cxx copied to clipboard

Enums in classes

Open steeve opened this issue 3 years ago • 2 comments

Consider the following class:

class foo {
    enum bar {
        ALICE = 0,      /// Perform linear interpolation on the table
        BOB = 1  /// Perform parabolic interpolation on the table
    }; 

    void set(bar value);

private:
    bar value;
};

Since foo is a class with methods, it seems it's not possible to use foo::ALICE or foo::BOB from cxx since a type can't be both an enum and a class.

Thank you for this great project!

steeve avatar Jan 03 '22 06:01 steeve

I would write that binding as:

// foo_bar.h

#pragma once
#include "path/to/foo.h"

using foo_bar = foo::bar;
// src/lib.rs

#[cxx::bridge]
mod ffi {
    #[repr(i32)]
    enum foo_bar {
        ALICE,
        BOB,
    }

    unsafe extern "C++" {
        include!("path/to/foo_bar.h");

        type foo;
        type foo_bar;

        fn set(self: Pin<&mut foo>, value: foo_bar);
    }
}

Then this is usable as foo.set(ffi::foo_bar::BOB).

If you want the enum variants available directly on foo so that callers do not need to use the separate foo_bar enum type, you can add:

impl ffi::foo {
    pub const ALICE: ffi::foo_bar = ffi::foo_bar::ALICE;
    pub const BOB: ffi::foo_bar = ffi::foo_bar::BOB;
}

dtolnay avatar Jan 03 '22 07:01 dtolnay

That's a great idea, thank you!

steeve avatar Jan 03 '22 09:01 steeve