Let say I want to bind a public instance variable 'height' from a class 'Image'. To my understanding, I should be able to do it this way Image class extending ObjectWrap
Napi::Function func = DefineClass(env, "Image", {
InstanceAccessor("height", &Image::GetHeight, &Image::SetHeight),
....
But compilation fails with error: 'No matching function found InstanceAccessor'. If I replace SetHeight with nullptr, the code compiles. I also saw some code examples on past issues that used nullptr in place of a setter. If InstanceAccessor is supposed to take a nullptr as 3rd argument then why does the 3rd argument even exists? How do I use a Setter so that executing image.height = 5 in nodejs side should call SetHieght()?
What does Image::SetHeight look like?
InstanceAccessor can take a setter function. You might be supplying an unsupported function type.
Something like this should work:
void Image::SetHeight(const Napi::CallbackInfo &info,
const Napi::Value &value) {
const auto arg = value.As<Napi::Number>();
const auto native_value = arg.Int32Value();
native_instance_->height = native_value;
}
I was using the regular function signature Napi::Value Image::SetImageHeight(const Napi::CallbackInfo &info); and expecting to receive value from info[0]. Changing it to your method signature fixed the issue. @ross-weir thanks a lot. How do you know this is the correct signature to use? I don't find it documented anywhere
I think I read through the source code a little bit to figure it out. I do remember the documentation lacking on code examples which would have been helpful. Maybe we can open a PR to add some? 馃憤
@ross-weir would be happy to have PR's for some additional examples :)
If I want to specify that I have no setter or no getter, should I pass nullptr?
Most helpful comment
@ross-weir would be happy to have PR's for some additional examples :)