quickjspp icon indicating copy to clipboard operation
quickjspp copied to clipboard

Enum classes

Open projectitis opened this issue 4 years ago • 5 comments

Hi ftk,

What is your suggested method of handling an enum class?

// c++
enum class DisplayMode {
    Cover,
    Contain,
    LetterBox,
};

// js
myObject.displayMode = DisplayMode.Contain;

Should I convert my native c++ classes to use enums with explicit (integer) values, and then define the enum purely in JS, like this?

// c++
enum DisplayModeT {
    Cover = 1,
    Contain = 2,
    LetterBox = 3,
} DisplayMode;

// js
DisplayMode = {
  Cover: 1,
  Contain : 2,
  LetterBox : 3
};
Object.freeze(DisplayMode);

myObject.displayMode = DisplayMode.Contain;

Or is there a quickjspp way? :)

projectitis avatar Aug 23 '21 09:08 projectitis

Although I do have it working with the 'freeze' workaround above, ES2020 supports static class properties, so I think the solution/question here is:

Is there a way to add a "static const" property using quickjspp?

// c++
class DisplayMode {
public:
    static const int Cover = 1;
    static const int Contain = 2;
    static const int LetterBox = 3;
}

module.class_<DisplayMode >( "DisplayMode " )
    .fun<&DisplayMode::Cover>( "Cover" )
    .fun<&DisplayMode::Contain>( "Contain" )
    .fun<&DisplayMode::LetterBox>( "LetterBox" );

/* js expected result
class DisplayMode {
    static Cover = 1;
    static Contain = 2;
    static LetterBox = 3;
}
*/

This results in a bunch of unresolved symbols when compiled. Am I doing it incorrectly, or are static properties not supported (yet).

projectitis avatar Aug 24 '21 23:08 projectitis

@projectitis my solution

#define ENUM_DEF(type)                                          \
  template <>                                                   \
  struct js_traits<type> {                                      \
    static type unwrap(JSContext* ctx, JSValue v) noexcept {    \
      uint32_t t;                                               \
      JS_ToUint32(ctx, &t, v);                                  \
      return type((uint16_t)t);                                 \
    }                                                           \
                                                                \
    static JSValue wrap(JSContext* ctx, type opcode) noexcept { \
      return JS_NewUint32(ctx, opcode);                         \
    }                                                           \
  }
ENUM_DEF(MethodItemType);

dodola avatar Jun 15 '22 08:06 dodola

How do you use it, @dodola?

projectitis avatar Jun 15 '22 09:06 projectitis

@projectitis example: https://github.com/dodola/quickjspp/blob/master/test/enum.cpp

dodola avatar Jun 17 '22 04:06 dodola

@projectitis simple enum support https://github.com/ftk/quickjspp/commit/0b725022bd9126a6cf4b862430ea113ac612b350

dodola avatar Jun 21 '22 03:06 dodola