js_utils.hpp
Tools for passing data between C++ and Javascript.
Functions
-
std::map<std::string, std::string> get_type_to_string_map()
This function returns a std::map mapping typeid names to the appropriate strings to describe those types in Javscript. This is useful when using getValue() from within MAIN_THREAD_EM_ASM macros.
For example, say we have a templated function that takes a pointer to type T. We find out the appropriate string for type T :
std::map<const char*, std::string> type_map = GetTypeToStringMap(); std::string type_string = type_map[typeid(T).name()];
Now we can pass type_string.c_str() into MAIN_THREAD_EM_ASM:
MAIN_THREAD_EM_ASM({ var value = getValue($0, $1); }, pointer, type_string.c_str();
-
template<typename C, class = typename C::value_type>
void pass_array_to_javascript(C values) This function can be called to pass an array, vector, or other container with contiguously stored data into Javascript. The array will be stored in emp.__incoming_array. Currently supports arrays containing all of the types defined in get_type_to_string_map, which are also all of the types that emscripten supports getting via pointer. This function also supports nested arrays, and arrays of objects created with introspective tuple structs.
-
template<std::size_t SIZE, typename T>
void pass_array_to_cpp(array<T, SIZE> &arr, bool recurse = false) This function lets you pass an array from javascript to C++! It takes a reference to the array as an argument and populates it with the contents of emp.__outgoing_array.
Currently accepts arrays of ints, floats, doubles, chars, and std::strings The size of the passed array must be equal to the size of the array stored in emp.__outgoing_array
-
template<typename T>
void pass_vector_to_cpp(vector<T> &arr, bool recurse = false) Same as pass_array_to_cpp, but lets you store values in a vector instead.
-
template<typename KEY_T, typename VAL_T>
void pass_map_to_javascript(const map<KEY_T, VAL_T> &dict) This function can be called to pass a map into JavaScript. The resulting JavaScript object will be stored in emp.__incoming_map.
- Parameters:
dict – the map being passed into JavaScript
-
template<typename KEY_T, typename VAL_T, size_t SIZE>
void pass_map_to_javascript(const array<KEY_T, SIZE> &keys, const array<VAL_T, SIZE> &values) This function can be called to pass two arrays of the same length into JavaScript (where a map is then created) One array should hold keys, and the other should hold values (note that the key-value pairs must line up across the arrays) The resulting JavaScript object will be stored in emp.__incoming_map.
- Parameters:
keys – an array holding the keys to the map
values – an array holding the values to the map
-
int GetViewPortSize()
Helper function that returns DOM view port size in pixels.