Skip to content

Conversation

FelixNumworks
Copy link

Fix #24324
Fix #19387
Fix #18585

This PR adds a bool asString parameter to embind enum declaration

enum_<MyEnum>("MyEnum"); // Defaults to false
enum_<MyEnum>("MyEnum", true); // asString

If asString is true, the enum is greatly simplified, since the name of a value is equivalent to the value itself.

MyEnum.ONE === "ONE" // true

myFuncTakingEnumParam(MyEnum.ONE);
myFuncTakingEnumParam("ONE");

We go from

export interface MyEnumValue<T extends number> {
  value: T;
}
export type MyEnum = MyEnumValue<0>|MyEnumValue<1>|MyEnumValue<2>;

interface EmbindModule {
  MyEnum: {valueOne: MyEnumValue<0>, valueTwo: MyEnumValue<1>, valueThree: MyEnumValue<2>};
};

to

export type MyEnum = 'valueOne'|'valueTwo'|'valueThree'

interface EmbindModule {
  MyEnum: {valueOne: 'valueOne', valueTwo: 'valueTwo', valueThree: 'valueThree'};
};

This doesn't conflict with current implementation of enums, as the bool default value is false

This is my first PR to emscripten, so I'm sorry in advance if it contains some obvious flaws ...
I really hope this gets into the main code, as it would really simplify enums handling

@FelixNumworks FelixNumworks changed the title feat(embind): add a way to register enums valus as plain string feat(embind): add a way to register enum values as plain string Sep 11, 2025
@kripken kripken requested a review from brendandahl September 11, 2025 22:56
destructorFunction: null,
});
exposePublicSymbol(name, ctor);
if (asString) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this doesn't have any shared code let's split it out into it's own function _embind_register_enum_string or something. I'm guessing users will only use one way other other, so then if it's a totally seperate function it will be easier to do dead code elimination.

});
Enum.values[enumValue] = Value;
Enum[name] = Value;
if (enumType.asString) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, split into its own function. I think you'll have to store on the enum class in c++ whether it's a string or not and call the correct register function from there.

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