val.h

TheEmbind C++ classemscripten::val (defined inval.h) is used totransliterate JavaScript code to C++.

Guide material for this class can be found inUsing val to transliterate JavaScript to C++.

classemscripten::val

This class is a C++ data type that can be used to represent (and provide convenient access to) any JavaScript object. You can use it to call a JavaScript object, read and write its properties, or coerce it to a C++ value like abool,int, orstd::string.

For example, the code below shows some simple JavaScript for making an XHR request on a URL:

varxhr=newXMLHttpRequest;xhr.open("GET","http://url");

This same code can be written in C++, usingglobal() to get the symbol for the globalXMLHttpRequest object and then using it to open a URL.

valxhr=val::global("XMLHttpRequest").new_();xhr.call<void>("open",std::string("GET"),std::string("http://url"));

You can test whether theopen method call was successful usingoperator[]() to read an object property, thenas() to coerce the type:

constchar*state;switch(xhr["readyState"].as<int>()){case0:state="UNSENT";break;case1:state="OPENED";break;default:state="etc";}

SeeUsing val to transliterate JavaScript to C++ for other examples.

Warning

JavaScript values can’t be shared across threads, so neither canval instances that bind them.

For example, if you want to cache some JavaScript global as aval, you need to retrieve and bind separate instances of that global by its name in each thread.The easiest way to do this is with athread_local declaration:

thread_localconstvalUint8Array=val::global("Uint8Array");
staticvalarray()

Creates and returns a newArray.

staticvalobject()

Creates and returns a newObject.

staticvalu8string(constchar*s)

Creates aval from a string literal in UTF-8 encoding.

staticvalu16string(constchar16_t*s)

Creates aval from a string literal in UTF-16 encoding.

staticvalundefined()

Creates aval that representsundefined.

staticvalnull()

Creates aval that representsnull.

EM_VALas_handle()const

Returns a raw handle representing thisval. This can be used forpassing raw value handles to JavaScript and retrieving the values on theother side viaEmval.toValue function. Example:

EM_JS(void,log_value,(EM_VALval_handle),{varvalue=Emval.toValue(val_handle);console.log(value);// 42});valfoo(42);log_value(foo.as_handle());
staticvaltake_ownership(EM_VALe)

Creates aval from a raw handle. This can be used for retrieving valuesfrom JavaScript, where the JavaScript side should wrap a value withEmval.toHandle, pass it to C++, and then C++ can usetake_ownershipto convert it to aval instance. Example:

EM_ASYNC_JS(EM_VAL,fetch_json_from_url,(constchar*url),{varurl=UTF8ToString(url);varresponse=awaitfetch(url);varjson=awaitresponse.json();returnEmval.toHandle(json);});valobj=val::take_ownership(fetch_json_from_url("https://httpbin.org/json"));std::stringauthor=obj["slideshow"]["author"].as<std::string>();
staticvalglobal(constchar*name)

Looks up a global value by the specifiedname.

staticvalmodule_property(constchar*name)

Looks up a value by the providedname on the Emscripten Module object.

explicitval(T&&value)

Constructor.

Creates aval by conversion from any Embind-compatible C++ type.For example,val(true) orval(std::string("foo")).

explicitval(constchar*v)

Constructs aval instance from a string literal.

val(val&&v)

Moves ownership of a value to a newval instance.

val(constval&v)

Creates another reference to the same value behind the providedval instance.

~val()

Removes the currently bound value by decreasing its refcount.

val&operator=(val&&v)

Removes a reference to the currently bound value and takes over the provided one.

val&operator=(constval&v)

Removes a reference to the currently bound value and creates another reference tothe value behind the providedval instance.

boolhasOwnProperty(constchar*key)const

Checks if the JavaScript object has own (non-inherited) property with the specified name.

valnew_(Args&&...args)const

Assumes that current value is a constructor, and creates an instance of it.Equivalent to a JavaScript expressionnew currentValue(…).

valoperator[](constT&key)const

Get the specified (key) property of a JavaScript object.

voidset(constK&key,constval&v)

Set the specified (key) property of a JavaScript object (accessed through aval) with the valuev.

valoperator()(Args&&...args)const

Assumes that current value is a function, and invokes it with provided arguments.

ReturnValuecall(constchar*name,Args&&...args)const

Invokes the specified method (name) on the current object with provided arguments.

Tas()const

Converts current value to the specified C++ type.

valtypeof()const

Returns the result of a JavaScripttypeof operator invoked on the current value.

std::vector<T>vecFromJSArray(constval&v)

Copies a JavaScript array into astd::vector<T>, converting each element via.as<T>().For a more efficient but unsafe version working with numbers, seeconvertJSArrayToNumberVector.

Parameters:

val v – The JavaScript array to be copied

Returns:

Astd::vector<T> made from the javascript array

std::vector<T>convertJSArrayToNumberVector(constval&v)

Converts a JavaScript array into astd::vector<T> efficiently, as if using the javascriptNumber() function on each element.This is way more efficient thanvecFromJSArray on any array with more than 2 values, but is not suitable for arrays of non-numeric values.No type checking is done, so any invalid array entry will silently be replaced by a NaN value (or 0 for integer types).

Parameters:

val v – The JavaScript (typed) array to be copied

Returns:

A std::vector<T> made from the javascript array

valawait()const

Pauses the C++ toawait thePromise / thenable.

Returns:

The fulfilled value.

Note

This method requiresASYNCIFY to be enabled.

valoperatorco_await()const

Theco_await operator allows awaiting JavaScript promises represented byval.

It’s compatible with any C++20 coroutines, but should be normally used insideaval-returning coroutine which will also become aPromise.

For example, it allows you to implement the equivalent of this JavaScriptasync/await function:

asyncfunctionfoo(){constresponse=awaitfetch("http://url");constjson=awaitresponse.json();returnjson;}export{foo};

as a C++ coroutine:

valfoo(){valresponse=co_awaitval::global("fetch")(std::string("http://url"));valjson=co_awaitresponse.call<val>("json");returnjson;}EMSCRIPTEN_BINDINGS(module){function("foo",&foo);}

Unlike theawait() method, it doesn’t need Asyncify as it uses native C++ coroutine transform.

Returns:

Aval representing the fulfilled value of this promise.