Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

How to export static constants? #84

Closed
VitaminCpp opened this issue Aug 24, 2018 · 4 comments
Closed

How to export static constants? #84

VitaminCpp opened this issue Aug 24, 2018 · 4 comments

Comments

@VitaminCpp
Copy link

I would like to write the following Javascript:

console.log(MyClass.VERSION);
var myClass = new MyClass(MyClass.MY_CONSTANT);

My current class wrapper looks like this:

MyClassWrapper myClassWrapper(isolate);
  myClassWrapper
    .ctor<MyClass::Type>()
    .set_const("MY_CONSTANT", &MyClass::MY_CONSTANT);

But as expected this wont work, because MY_CONSTANT is a V8 prototype property instead of a V8 ObjectTemplate property.

But because I can't break our current API, I would need some workaround without having to change my existing API.

@VitaminCpp
Copy link
Author

I would suggest the following proposal for class.hpp:

/// Set a static value
template<typename Value>
class_& set_static(char const* name, Value const& value, bool readonly = false)
{
v8::HandleScope scope(isolate());

class_info_.js_function_template()->GetFunction(isolate()->GetCurrentContext()).ToLocalChecked()
    ->DefineOwnProperty(isolate()->GetCurrentContext(),
    v8pp::to_v8(isolate(), name), to_v8(isolate(), value),
    v8::PropertyAttribute(v8::DontDelete | (readonly ? v8::ReadOnly : 0))).FromJust();
return *this;
}

So you can define (const) static members this way:

MyClassWrapper myClassWrapper(isolate);
  myClassWrapper
    .ctor<MyClass::Type>()
    .set_static("MY_CONSTANT", &MyClass::MY_READONLY_CONSTANT, true)
    .set_static("MY_CONSTANT", &MyClass::MY_CONSTANT);

@pmed
Copy link
Owner

pmed commented Aug 25, 2018 via email

@atvise
Copy link

atvise commented Sep 3, 2018

Hi @pmed,

if I understood you right that would mean that every variable set through set_const would be accessible without a class instantiation. Furthermore the static variable would only available as const variable and for some applications there is maybe a need of writable static variables.

So I think it would be best if there is a seperate set of functions which register either member variables (const or writeable) or static variables (const or writeable) of a class like @VitaminCpp made an example of.

Regards,
atvise

@pmed
Copy link
Owner

pmed commented Dec 29, 2018

Fixed in #89, but note that static property definition works only at the end of v8pp::class_ declaration.

@pmed pmed closed this as completed Dec 29, 2018
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants