cxx
cxx copied to clipboard
Enums in classes
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!
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;
}
That's a great idea, thank you!