node.jsnode-addon-apin-api

How to use InstanceMethod() to wrap a method returning an Object?


Working on creating an add-on that will return an Object to the node environment. Basing my work on Atul Anand's introduction to N-API in C++, the methods of the class object are wrapped in InstanceMethod() to expose them; but that function wants a method that returns a Napi::Value. I can't figure out the invocation to convert the C++ pointer into a Value; Value::From(env, ptr) errors (Visual C++ 2017) with "cannot convert from 'initializer list' to 'Napi::Value'".


Solution

  • It seems that even as I was asking here, someone else was asking at the Node-API-Addon github site. The solution initially posted to the user's question was what I needed to get my code working.

    In short (and obvious in retrospect): the C++ pointer is useless in JavaScript, the method needs to return a JavaScript object wrapping the C++ object. The JS object is maintained within a napi_ref (Napi::Reference) and the reference's Value() is what gets returned from the access method.