I am writing a C++ module for Node.js that wraps a C library, so we can use the C library from JavaScript. One of the functions in the C library takes an enum parameter, with the enum values included in the corresponding header file. I would like to export the enum values as integers from the C++ module so the Node.js application wouldn't have to hardcode the value. Here is the basic idea:
C:
typedef enum
{
LOGLEVEL_ERROR = 0,
LOGLEVEL_WARN,
LOGLEVEL_INFO
} log_level_t;
write_to_log(log_level_t level, char* message);
C++:
Logger::Write(int level, char* message)
{
write_to_log(level, message);
}
Node.js:
// This is what I want:
logger.write(logger.ERROR, "Oh no! Something bad happened.");
How do I expose LOGLEVEL_ERROR
from C++ so I can use logger.ERROR
in JS? (I would even be OK with logger.LOGLEVEL_ERROR
in JS.) I found an old Node.js native module that used a macro EXPORT_INT32
but this doesn't seem to exist anymore (I'm using Node.js 0.8.8).
Wrap the number, like this:
HandleScope scope;
/** method code here **/
Local<Number> num = Number::New(5);
return scope.Close(num);
See my module kexec
as an example: https://github.com/jprichardson/node-kexec/blob/master/src/kexec.cc
Edit: Ooops, I didn't entirely read your question clearly. I would declared those values in JS.
Edit 2: Upon further inspection, it seems that it may be a bit harry, but possible. It seems that you might want to use V8 Juice.
Here is the relevant section: Converting Enums
Hope this helps some, but the easiest route would be to just declare them in JavaScript.
This is what I ended up doing:
Local<Object> instance = constructor->NewInstance(2, argv);
Local<Object> logLevel = Object::New();
logLevel->Set(String::NewSymbol("ERROR"), cvv8::CastToJS(LOGLEVEL_ERROR), ReadOnly);
logLevel->Set(String::NewSymbol("WARN"), cvv8::CastToJS(LOGLEVEL_WARN), ReadOnly);
logLevel->Set(String::NewSymbol("INFO"), cvv8::CastToJS(LOGLEVEL_INFO), ReadOnly);
instance->Set(String::NewSymbol("Level"), logLevel, ReadOnly);
Then from JavaScript you can access logger.Level.ERROR
.