TL;DR: If you need to produce a JS::Value from some C++ type, use
mozilla::dom::ToJSValue. Anything else will probably need to be
search-and-replaced out of the codebase later.
Background: There are some situations in which it's not possible to just
use WebIDL bindings to handle conversions from C++ values to JS values.
Examples include resolving a Promise with the value, calls to XPCOM
APIs that take "jsval" in the xpidl, and various interactions with JSAPI
that might become more prevalent as there is tighter coupling between
EcmaScript and other parts of the web platform. Furthermore, we might
end up with some .... interesting rules about which compartment should
be used when allocating objects when called via Xrays.
To address all this, we now have a mozilla/dom/ToJSValue.h header, which
provides various overloads of the mozilla::dom::ToJSValue function. All
overloads take a JSContext*, a C++ value, and a JS::MutableHandleValue
to put the resulting JS::Value into. These functions should be used for
all your "create a JS::Value in C++" needs.
Promises make use of this infrastructure automatically via the
single-argument Promise::MaybeResolve/MaybeReject, but other code that
for some reason needs to create JS values can and should be using this
as well. You can see an example use in
http://hg.mozilla.org/mozilla-central/diff/4182ec5042d5/dom/mobilemessage/src/SmsFilter.cpp
The following C++ types are currently supported:
1) nsString.
2) int32_t, uint32_t, int64_t, uint64_t.
3) float, double.
4) A reference to a WebIDL-binding object which inherits from both
nsWrapperCache and nsISupports.
5) A reference to any C++ type which singly-inherits from nsISupports
(e.g. any nsIFoo).
6) An nsRefPtr or nsCOMPtr around an object that satisfies the
conditions of #4 or #5.
7) const nsTArray<T>, where T is any supported type.
8) const FallibleTArray<T>, where T is any supported type.
9) const T[N], where T is any supported type and N is an integer.
10) WebIDL dictionaries.
There is also an explicit four-argument form of ToJSValue that can
handle an arbitrary (T*, length) pair and produces an array; you can see
an example use in
http://hg.mozilla.org/mozilla-central/diff/4182ec5042d5/content/canvas/src/WebGLContextGL.cpp
We will add other types as needed, of course, but I expect that the
above should cover most current use cases.
If you find yourself reaching for JS_NewArrayObject, stop, take a deep
breath, and use ToJSValue instead. ;)
-Boris
_______________________________________________
dev-platform mailing list
[email protected]
https://lists.mozilla.org/listinfo/dev-platform