emscripten.h

This page documents the public C++ APIs provided byemscripten.h.

Emscripten uses existing/familiar APIs where possible (for example:SDL). This API provides C++ support for capabilities that are specific to JavaScript or the browser environment, or for which there is no existing API.

Inline assembly/JavaScript

Guide material for the following APIs can be found inCalling JavaScript from C/C++.

Defines

EM_JS(return_type,function_name,arguments,code)

Convenient syntax for JavaScript library functions.

This allows you to declare JavaScript in your C code as a function, which canbe called like a normal C function. For example, the following C program woulddisplay two alerts if it was compiled with Emscripten and run in the browser:

EM_JS(void, two_alerts, (), {  alert('hai');  alert('bai');});int main() {  two_alerts();  return 0;}

Arguments can be passed as normal C arguments, and have the same name in theJavaScript code. These arguments can either be of typeint32_t ordouble.

EM_JS(void, take_args, (int x, float y), {  console.log('I received: ' + [x, y]);});int main() {  take_args(100, 35.5);  return 0;}

Null-terminated C strings can also be passed intoEM_JS functions, but tooperate on them, they need to be copied out from the heap to convert tohigh-level JavaScript strings.

EM_JS(void, say_hello, (const char* str), {  console.log('hello ' + UTF8ToString(str));}

In the same manner, pointers to any type (includingvoid*) can be passedinsideEM_JS code, where they appear as integers likechar* pointersabove did. Accessing the data can be managed by reading the heap directly.

EM_JS(void, read_data, (int* data), {  console.log('Data: ' + HEAP32[data>>2] + ', ' + HEAP32[(data+4)>>2]);});int main() {  int arr[2] = { 30, 45 };  read_data(arr);  return 0;}

In addition, EM_JS functions can return a value back to C code. The outputvalue is passed back with areturn statement:

EM_JS(int, add_forty_two, (int n), {  return n + 42;});EM_JS(int, get_memory_size, (), {  return HEAP8.length;});int main() {  int x = add_forty_two(100);  int y = get_memory_size();  // ...}

Strings can be returned back to C from JavaScript, but one needs to be carefulabout memory management.

EM_JS(char*, get_unicode_str, (), {  var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.';  // 'jsString.length' would return the length of the string as UTF-16  // units, but Emscripten C strings operate as UTF-8.  return stringToNewUTF8(jsString);});int main() {  char* str = get_unicode_str();  printf("UTF8 string says: %s\n", str);  // Each call to _malloc() must be paired with free(), or heap memory will leak!  free(str);  return 0;}
EM_ASM(...)

Convenient syntax for inline assembly/JavaScript.

This allows you to declare JavaScript in your C code “inline”, which is then executed when your compiled code is run in the browser. For example, the following C code would display two alerts if it was compiled with Emscripten and run in the browser:

EM_ASM(alert('hai'); alert('bai'));

Arguments can be passed inside the JavaScript code block, where they arrive as variables$0,$1 etc. These arguments can either be of typeint32_t ordouble.

EM_ASM({  console.log('I received: ' + [$0, $1]);}, 100, 35.5);

Note the{ and}.

Null-terminated C strings can also be passed intoEM_ASM blocks, but to operate on them, they need to be copied out from the heap to convert to high-level JavaScript strings.

EM_ASM(console.log('hello ' + UTF8ToString($0)), "world!");

In the same manner, pointers to any type (includingvoid*) can be passed insideEM_ASM code, where they appear as integers likechar* pointers above did. Accessing the data can be managed by reading the heap directly.

int arr[2] = { 30, 45 };EM_ASM({  console.log('Data: ' + HEAP32[$0>>2] + ', ' + HEAP32[($0+4)>>2]);}, arr);

Note

  • As of Emscripten1.30.4, the contents ofEM_ASM code blocks appear inside the normal JS file, and as result, Closure compiler and other JavaScript minifiers will be able to operate on them. You may need to use safety quotes in some places (a['b'] instead ofa.b) to avoid minification from occurring.

  • The C preprocessor does not have an understanding of JavaScript tokens, and as a result, if thecode block contains a comma character,, it may be necessary to wrap the code block inside parentheses. For example, codeEM_ASM(return[1,2,3].length); will not compile, butEM_ASM((return[1,2,3].length)); does.

EM_ASM_INT(code,...)

This macro, as well asEM_ASM_DOUBLE andEM_ASM_PTR,behave likeEM_ASM, but in addition they also return a value backto C code. The output value is passed back with areturn statement:

int x = EM_ASM_INT({  return $0 + 42;}, 100);int y = EM_ASM_INT(return HEAP8.length);
EM_ASM_PTR(code,...)

Similar toEM_ASM_INT but for a pointer-sized return values.When building with-sMEMORY64 this results in i64 return value, otherwiseit results in an i32 return value.

Strings can be returned back to C from JavaScript, but one needs to be carefulabout memory management.

char *str = (char*)EM_ASM_PTR({  var jsString = 'Hello with some exotic Unicode characters: Tässä on yksi lumiukko: ☃, ole hyvä.';  var lengthBytes = lengthBytesUTF8(jsString)+1;  // 'jsString.length' would return the length of the string as UTF-16  // units, but Emscripten C strings operate as UTF-8.  return stringToNewUTF8(jsString);});printf("UTF8 string says: %s\n", str);free(str); // Each call to _malloc() must be paired with free(), or heap memory will leak!
EM_ASM_DOUBLE(code,...)

Similar toEM_ASM_INT but for adouble return value.

MAIN_THREAD_EM_ASM(code,...)

This behaves likeEM_ASM, but does the call on the main thread. This isuseful in a pthreads build, when you want to interact with the DOM from apthread; this basically proxies the call for you.

This call is proxied in a synchronous way to the main thread, that is,execution will resume after the main thread has finished running the JS.Synchronous proxying also makes it possible to return a value, see the nexttwo variants.

MAIN_THREAD_EM_ASM_INT(code,...)

Similar toMAIN_THREAD_EM_ASM but returns anint value.

MAIN_THREAD_EM_ASM_DOUBLE(code,...)

Similar toMAIN_THREAD_EM_ASM but returns adouble value.

MAIN_THREAD_EM_ASM_PTR(code,...)

Similar toMAIN_THREAD_EM_ASM but returns a pointer value.

MAIN_THREAD_ASYNC_EM_ASM(code,...)

Similar toMAIN_THREAD_EM_ASM but is proxied in anasynchronous way, that is, the main thread will receive a request to runthe code, and will run it when it can; the worker will not wait for that.(Note that if this is called on the main thread, then there is nothing toproxy, and the JS is executed immediately and synchronously.)

Calling JavaScript From C/C++

Guide material for the following APIs can be found inCalling JavaScript from C/C++.

Function pointer types for callbacks

The following types are used to define function callback signatures used in a number of functions in this file.

typeem_callback_func

General function pointer type for use in callbacks with no parameters.

Defined as:

typedefvoid(*em_callback_func)(void)
typeem_arg_callback_func

Generic function pointer type for use in callbacks with a singlevoid* parameter.

This type is used to define function callbacks that need to pass arbitrary data. For example,emscripten_set_main_loop_arg() sets user-defined data, and passes it to a callback of this type on completion.

Defined as:

typedefvoid(*em_arg_callback_func)(void*)
typeem_str_callback_func

General function pointer type for use in callbacks with a C string (constchar*) parameter.

This type is used for function callbacks that need to be passed a C string. For example, it is used inemscripten_async_wget() to pass the name of a file that has been asynchronously loaded.

Defined as:

typedefvoid(*em_str_callback_func)(constchar*)

Functions

voidemscripten_run_script(constchar*script)

Interface to the underlying JavaScript engine. This function willeval() the given script. Note: If-sDYNAMIC_EXECUTION=0 is set, this function will not be available.

This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread().

Parameters:
  • script (constchar*) – The script to evaluate.

Return type:

void

intemscripten_run_script_int(constchar*script)

Interface to the underlying JavaScript engine. This function willeval() the given script. Note: If-sDYNAMIC_EXECUTION=0 is set, this function will not be available.

This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread().

Parameters:
  • script (constchar*) – The script to evaluate.

Returns:

The result of the evaluation, as an integer.

Return type:

int

char*emscripten_run_script_string(constchar*script)

Interface to the underlying JavaScript engine. This function willeval() the given script. Note that this overload uses a single buffer shared between calls. Note: If-sDYNAMIC_EXECUTION=0 is set, this function will not be available.

This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread().

Parameters:
  • script (constchar*) – The script to evaluate.

Returns:

The result of the evaluation, as a string.

Return type:

char*

voidemscripten_async_run_script(constchar*script,intmillis)

Asynchronously run a script, after a specified amount of time.

This function can be called from a pthread, and it is executed in the scope of the Web Worker that is hosting the pthread. To evaluate a function in the scope of the main runtime thread, see the function emscripten_sync_run_in_main_runtime_thread().

Parameters:
  • script (constchar*) – The script to evaluate.

  • millis (int) – The amount of time before the script is run, in milliseconds.

Return type:

void

voidemscripten_async_load_script(constchar*script,em_callback_funconload,em_callback_funconerror)

Asynchronously loads a script from a URL.

This integrates with the run dependencies system, so your script can calladdRunDependency multiple times, prepare various asynchronous tasks, and callremoveRunDependency on them; when all are complete (or if there were no run dependencies to begin with),onload is called. An example use for this is to load an asset module, that is, the output of the file packager.

This function is currently only available in main browser thread, and it will immediately fail by calling the supplied onerror() handler if called in a pthread.

Parameters:
  • script (constchar*) – The script to evaluate.

  • onload (em_callback_func) – A callback function, with no parameters, that is executed when the script has fully loaded.

  • onerror (em_callback_func) – A callback function, with no parameters, that is executed if there is an error in loading.

Return type:

void

Browser Execution Environment

Guide material for the following APIs can be found inEmscripten Runtime Environment.

Functions

voidemscripten_set_main_loop(em_callback_funcfunc,intfps,boolsimulate_infinite_loop)

Set a C function as the main event loop for the calling thread.

If the main loop function needs to receive user-defined data, useemscripten_set_main_loop_arg() instead.

The JavaScript environment will call that function at a specified number of frames per second. If called on the main browser thread, setting 0 or a negative value as thefps will use the browser’srequestAnimationFrame mechanism to call the main loop function. This isHIGHLY recommended if you are doing rendering, as the browser’srequestAnimationFrame will make sure you render at a proper smooth rate that lines up properly with the browser and monitor. If you do not render at all in your application, then you should pick a specific frame rate that makes sense for your code.

Ifsimulate_infinite_loop is true, the function will throw an exception in order to stop execution of the caller. This will lead to the main loop being entered instead of code after the call toemscripten_set_main_loop() being run, which is the closest we can get to simulating an infinite loop (we do something similar inglutMainLoop inGLUT). If this parameter isfalse, then the behavior is the same as it was before this parameter was added to the API, which is that execution continues normally. Note that in both cases we do not run global destructors,atexit, etc., since we know the main loop will still be running, but if we do not simulate an infinite loop then the stack will be unwound. That means that ifsimulate_infinite_loop isfalse, and you created an object on the stack, it will be cleaned up before the main loop is called for the first time.

This function can be called in a pthread, in which case the callback loop will be set up to be called in the context of the calling thread. In order for the loop to work, the calling thread must regularly “yield back” to the browser by exiting from its pthread main function, since the callback will be able to execute only when the calling thread is not executing any other code. This means that running a synchronously blocking main loop is not compatible with the emscripten_set_main_loop() function.

SincerequestAnimationFrame() API is not available in web workers, when calledemscripten_set_main_loop() in a pthread withfps <= 0, the effect of syncing up to the display’s refresh rate is emulated, and generally will not precisely line up with vsync intervals.

Tip

There can be onlyone main loop function at a time, per thread. To change the main loop function, firstcancel the current loop, and then call this function to set another.

Note

Seeemscripten_set_main_loop_expected_blockers(),emscripten_pause_main_loop(),emscripten_resume_main_loop() andemscripten_cancel_main_loop() for information about blocking, pausing, and resuming the main loop of the calling thread.

Note

Calling this function overrides the effect of any previous calls toemscripten_set_main_loop_timing() in the calling thread by applying the timing mode specified by the parameterfps. To specify a different timing mode for the current thread, call the functionemscripten_set_main_loop_timing() after setting up the main loop.

Note

Currently, usingthe new Wasm exception handling andsimulate_infinite_loop == true at the same time does not work yet in C++ projects that have objects with destructors on the stack at the time of the call.

Parameters:
  • func (em_callback_func) – C function to set as main event loop for the calling thread.

  • fps (int) – Number of frames per second that the JavaScript will call the function. Settingint<=0 (recommended) uses the browser’srequestAnimationFrame mechanism to call the function.

  • simulate_infinite_loop (bool) – If true, this function will throw an exception in order to stop execution of the caller.

voidemscripten_set_main_loop_arg(em_arg_callback_funcfunc,void*arg,intfps,boolsimulate_infinite_loop)

Set a C function as the main event loop for the calling thread, passing it user-defined data.

See also

The information inemscripten_set_main_loop() also applies to this function.

Parameters:
  • func (em_arg_callback_func) – C function to set as main event loop. The function signature must have avoid* parameter for passing thearg value.

  • arg (void*) – User-defined data passed to the main loop function, untouched by the API itself.

  • fps (int) – Number of frames per second at which the JavaScript will call the function. Settingint<=0 (recommended) uses the browser’srequestAnimationFrame mechanism to call the function.

  • simulate_infinite_loop (bool) – If true, this function will throw an exception in order to stop execution of the caller.

voidemscripten_push_main_loop_blocker(em_arg_callback_funcfunc,void*arg)
voidemscripten_push_uncounted_main_loop_blocker(em_arg_callback_funcfunc,void*arg)

Add a function thatblocks the main loop for the calling thread.

The function is added to the back of a queue of events to be blocked; the main loop will not run until all blockers in the queue complete.

In the “counted” version, blockers are counted (internally) andModule.setStatus is called with some text to report progress (setStatus is a general hook that a program can define in order to show processing updates).

Note

  • Main loop blockers block the main loop from running, and can be counted to show progress. In contrast,emscripten_async_call() is not counted, does not block the main loop, and can fire at a specific time in the future.

Parameters:
  • func (em_arg_callback_func) – The main loop blocker function. The function signature must have avoid* parameter for passing thearg value.

  • arg (void*) – User-defined arguments to pass to the blocker function.

Return type:

void

voidemscripten_pause_main_loop(void)
voidemscripten_resume_main_loop(void)

Pause and resume the main loop for the calling thread.

Pausing and resuming the main loop is useful if your app needs to perform some synchronous operation, for example to load a file from the network. It might be wrong to run the main loop before that finishes (the original code assumes that), so you can break the code up into asynchronous callbacks, but you must pause the main loop until they complete.

Note

These are fairly low-level functions.emscripten_push_main_loop_blocker() (and friends) provide more convenient alternatives.

voidemscripten_cancel_main_loop(void)

Cancels the main event loop for the calling thread.

See alsoemscripten_set_main_loop() andemscripten_set_main_loop_arg() for information about setting and using the main loop.

Note

This function cancels the main loop, which means that it will no longer be called. No other changes occur to control flow. In particular, if you started the main loop with thesimulate_infinite_loop option, you can still cancel the main loop, but execution will not continue in the code right after setting the main loop (we do not actually run an infinite loop there - that’s not possible in JavaScript, so to simulate an infinite loop we halt execution at that stage, and then the next thing that runs is the main loop itself, so it seems like an infinite loop has begun there; canceling the main loop sort of breaks the metaphor).

intemscripten_set_main_loop_timing(intmode,intvalue)

Specifies the scheduling mode that the main loop tick function of the calling thread will be called with.

This function can be used to interactively control the rate at which Emscripten runtime drives the main loop specified by calling the functionemscripten_set_main_loop(). In native development, this corresponds with the “swap interval” or the “presentation interval” for 3D rendering. The new tick interval specified by this function takes effect immediately on the existing main loop, and this function must be called only after setting up a main loop viaemscripten_set_main_loop().

param int mode:

The timing mode to use. Allowed values are EM_TIMING_SETTIMEOUT, EM_TIMING_RAF and EM_TIMING_SETIMMEDIATE.

Parameters:
  • value (int) –

    The timing value to activate for the main loop. This value interpreted differently according to themode parameter:

    • Ifmode is EM_TIMING_SETTIMEOUT, thenvalue specifies the number of milliseconds to wait between subsequent ticks to the main loop and updates occur independent of the vsync rate of the display (vsync off). This method uses the JavaScriptsetTimeout function to drive the animation.

    • Ifmode is EM_TIMING_RAF, then updates are performed using therequestAnimationFrame function (with vsync enabled), and this value is interpreted as a “swap interval” rate for the main loop. The value of1 specifies the runtime that it should render at every vsync (typically 60fps), whereas the value2 means that the main loop callback should be called only every second vsync (30fps). As a general formula, the valuen means that the main loop is updated at every n’th vsync, or at a rate of60/n for 60Hz displays, and120/n for 120Hz displays.

    • Ifmode is EM_TIMING_SETIMMEDIATE, then updates are performed using thesetImmediate function, or if not available, emulated viapostMessage. SeesetImmediate on MDN <https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate> for more information. Note that this mode isstrongly not recommended to be used when deploying Emscripten output to the web, since it depends on an unstable web extension that is in draft status, browsers other than IE do not currently support it, and its implementation has been considered controversial in review.

Return type:

int

Returns:

The value 0 is returned on success, and a nonzero value is returned on failure. A failure occurs if there is no main loop active before calling this function.

Note

Browsers heavily optimize towards usingrequestAnimationFrame for animation instead of the other provided modes. Because of that, for best experience across browsers, calling this function withmode=EM_TIMING_RAF andvalue=1 will yield best results. Using the JavaScriptsetTimeout function is known to cause stutter and generally worse experience than using therequestAnimationFrame function.

Note

There is a functional difference betweensetTimeout andrequestAnimationFrame: If the user minimizes the browser window or hides your application tab, browsers will typically stop callingrequestAnimationFrame callbacks, butsetTimeout-based main loop will continue to be run, although with heavily throttled intervals. SeesetTimeout on MDN <https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout#Inactive_tabs> for more information.

voidemscripten_get_main_loop_timing(int*mode,int*value)

Returns the current main loop timing mode that is in effect. For interpretation of the values, see the documentation of the functionemscripten_set_main_loop_timing(). The timing mode is controlled by calling the functionsemscripten_set_main_loop_timing() andemscripten_set_main_loop().

param mode:

If not null, the used timing mode is returned here.

type mode:

int*

param value:

If not null, the used timing value is returned here.

type value:

int*

voidemscripten_set_main_loop_expected_blockers(intnum)

Sets the number of blockers that are about to be pushed.

The number is used for reporting therelative progress through a set of blockers, after which the main loop will continue.

For example, a game might have to run 10 blockers before starting a new level. The operation would first set this value as ‘10’ and then push the 10 blockers. When the 3rd blocker (say) completes, progress is displayed as 3/10.

Parameters:
  • num (int) – The number of blockers that are about to be pushed.

voidemscripten_async_call(em_arg_callback_funcfunc,void*arg,intmillis)

Call a C function asynchronously, that is, after returning control to the JavaScript event loop.

This is done by asetTimeout.

When building natively this becomes a simple direct call, afterSDL_Delay (you must includeSDL.h for that).

Ifmillis is negative, the browser’srequestAnimationFrame mechanism is used. (Note that 0 means thatsetTimeout is still used, which basically means “run asynchronously as soon as possible”.)

Parameters:
  • func (em_arg_callback_func) – The C function to call asynchronously. The function signature must have avoid* parameter for passing thearg value.

  • arg (void*) – User-defined argument to pass to the C function.

  • millis (int) – Timeout before function is called.

voidemscripten_exit_with_live_runtime(void)

Stops the current thread of execution, but leaves the runtime alive so that you can continue to run code later (so global destructors etc., are not run). Note that the runtime is kept alive automatically when you do an asynchronous operation likeemscripten_async_call(), so you don’t need to call this function for those cases.

In a multithreaded application, this just exits the current thread (and allows running code later in the Web Worker in which it runs).

voidemscripten_force_exit(intstatus)

Shuts down the runtime and exits (terminates) the program, as if you calledexit().

The difference is thatemscripten_force_exit will shut down the runtime even if you previously calledemscripten_exit_with_live_runtime() or otherwise kept the runtime alive. In other words, this method gives you the option to completely shut down the runtime after it was kept alive beyond the completion ofmain().

Note that ifEXIT_RUNTIME is not set (which is the case by default) then the runtime cannot be shut down, as we do not include the code to do so. Build with-sEXIT_RUNTIME if you want to be able to exit the runtime.

Parameters:
  • status (int) – The same as for thelibc functionexit().

doubleemscripten_get_device_pixel_ratio(void)

Returns the value ofwindow.devicePixelRatio.

Return type:

double

Returns:

The pixel ratio or 1.0 if not supported.

char*emscripten_get_window_title()

Returns the window title.

The returned string will be valid until the next call of the function

voidemscripten_set_window_title(char*title)

Sets the window title.

voidemscripten_get_screen_size(int*width,int*height)

Returns the width and height of the screen.

voidemscripten_hide_mouse(void)

Hide the OS mouse cursor over the canvas.

Note that SDL’sSDL_ShowCursor command shows and hides the SDL cursor, not the OS one. This command is useful to hide the OS cursor if your app draws its own cursor.

doubleemscripten_get_now(void)

Returns the highest-precision representation of the current time that the browser provides.

This uses eitherDate.now orperformance.now. The result is not an absolute time, and is only meaningful in comparison to other calls to this function.

Return type:

double

Returns:

The current time, in milliseconds (ms).

floatemscripten_random(void)

Generates a random number in the range 0-1. This maps toMath.random().

Return type:

float

Returns:

A random number.

Asynchronous File System API

Typedefs

typeem_async_wget_onload_func

Function pointer type for theonload callback ofemscripten_async_wget_data() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_async_wget_onload_func)(void*,void*,int)
typeem_async_wget2_onload_func

Function pointer type for theonload callback ofemscripten_async_wget2() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_async_wget2_onload_func)(void*,constchar*)
typeem_async_wget2_onstatus_func

Function pointer type for theonerror andonprogress callbacks ofemscripten_async_wget2() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_async_wget2_onstatus_func)(void*,int)
typeem_async_wget2_data_onload_func

Function pointer type for theonload callback ofemscripten_async_wget2_data() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_async_wget2_data_onload_func)(unsigned,void*,void*,unsigned)
typeem_async_wget2_data_onerror_func

Function pointer type for theonerror callback ofemscripten_async_wget2_data() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_async_wget2_data_onerror_func)(unsigned,void*,int,constchar*)
typeem_async_wget2_data_onprogress_func

Function pointer type for theonprogress callback ofemscripten_async_wget2_data() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_async_wget2_data_onprogress_func)(unsigned,void*,int,int)
typeem_run_preload_plugins_data_onload_func

Function pointer type for theonload callback ofemscripten_run_preload_plugins_data() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_run_preload_plugins_data_onload_func)(void*,constchar*)

Functions

voidemscripten_async_wget(constchar*url,constchar*file,em_str_callback_funconload,em_str_callback_funconerror)

Loads a file from a URL asynchronously.

In addition to fetching the URL from the network, preload plugins are executed so that the data is usable inIMG_Load and so forth (we asynchronously do the work to make the browser decode the image or audio etc.). SeePreloading files for more information on preloading files.

When the file is ready theonload callback will be called. If any error occursonerror will be called. The callbacks are called with the file as their argument.

Parameters:
  • url (constchar*) – The URL to load.

  • file (constchar*) – The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function.

  • onload (em_str_callback_func) –

    Callback on successful load of the file. The callback function parameter value is:

    • (const char)* : The name of thefile that was loaded from the URL.

  • onerror (em_str_callback_func) –

    Callback in the event of failure. The callback function parameter value is:

    • (const char)* : The name of thefile that failed to load from the URL.

voidemscripten_async_wget_data(constchar*url,void*arg,em_async_wget_onload_funconload,em_arg_callback_funconerror)

Loads a buffer from a URL asynchronously.

This is the “data” version ofemscripten_async_wget().

Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up forIMG_Load and so forth (IMG_Load etc. work on files).

When the file is ready then theonload callback will be called. If any error occurredonerror will be called.

Parameters:
  • url (constchar*) – The URL of the file to load.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • onload (em_async_wget_onload_func) –

    Callback on successful load of the URL into the buffer. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

    • (void)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time.

    • (int) : The size of the buffer, in bytes.

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

intemscripten_async_wget2(constchar*url,constchar*file,constchar*requesttype,constchar*param,void*arg,em_async_wget2_onload_funconload,em_async_wget2_onstatus_funconerror,em_async_wget2_onstatus_funconprogress)

Loads a file from a URL asynchronously.

This is anexperimental “more feature-complete” version ofemscripten_async_wget().

Preload plug-ins are at this timenot executed on the downloaded data. You may want to callemscripten_run_preload_plugins() in theonload callback if you want to be able to use the downloaded file withIMG_Load and such.

When the file is ready theonload callback will be called with the object pointers given inarg andfile. During the download theonprogress callback is called.

Parameters:
  • url (constchar*) – The URL of the file to load.

  • file (constchar*) – The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function.

  • requesttype (constchar*) – ‘GET’ or ‘POST’.

  • param (constchar*) – Request parameters for POST requests (seerequesttype). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g.key=value&key2=value2.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • onload (em_async_wget2_onload_func) –

    Callback on successful load of the file. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

    • (const char)* : Thefile passed to the original call.

  • onerror (em_async_wget2_onstatus_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

    • (int) : The HTTP status code.

  • onprogress (em_async_wget2_onstatus_func) –

    Callback during load of the file. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

    • (int) : The progress (percentage completed).

Returns:

A handle to request (int) that can be used toabort the request.

intemscripten_async_wget2_data(constchar*url,constchar*requesttype,constchar*param,void*arg,intfree,em_async_wget2_data_onload_funconload,em_async_wget2_data_onerror_funconerror,em_async_wget2_data_onprogress_funconprogress)

Loads a buffer from a URL asynchronously.

This is the “data” version ofemscripten_async_wget2(). It is anexperimental “more feature complete” version ofemscripten_async_wget_data().

Instead of writing to a file, this function writes to a buffer directly in memory. This avoids the overhead of using the emulated file system; note however that since files are not used, it cannot run preload plugins to set things up forIMG_Load and so forth (IMG_Load etc. work on files).

When the file is ready theonload callback will be called with the object pointers given inarg, a pointer to the buffer in memory, and an unsigned integer containing the size of the buffer. During the download theonprogress callback is called with progress information. If an error occurs,onerror will be called with the HTTP status code and a string containing the status description.

Parameters:
  • url (constchar*) – The URL of the file to load.

  • requesttype (constchar*) – ‘GET’ or ‘POST’.

  • param (constchar*) – Request parameters for POST requests (seerequesttype). The parameters are specified in the same way as they would be in the URL for an equivalent GET request: e.g.key=value&key2=value2.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • free (int) – Tells the runtime whether to free the returned buffer afteronload is complete. Iffalse freeing the buffer is the receiver’s responsibility.

  • onload (em_async_wget2_data_onload_func) –

    Callback on successful load of the file. The callback function parameter values are:

    • (unsigned) : Handle to the request

    • (void)* : Equal toarg (user defined data).

    • (void)* : A pointer to the buffer in memory.

    • (unsigned) : The size of the buffer (in bytes).

  • onerror (em_async_wget2_data_onerror_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (unsigned) : Handle to the request

    • (void)* : Equal toarg (user defined data).

    • (int) : The HTTP error code.

    • (const char)* : A string with the status description.

  • onprogress (em_async_wget2_data_onprogress_func) –

    Callback called (regularly) during load of the file to update progress. The callback function parameter values are:

    • (unsigned) : Handle to the request

    • (void)* : Equal toarg (user defined data).

    • (int) : The number of bytes loaded.

    • (int) : The total size of the data in bytes, or zero if the size is unavailable.

Returns:

A handle to request (int) that can be used toabort the request.

voidemscripten_async_wget2_abort(inthandle)

Abort an asynchronous request raised usingemscripten_async_wget2() oremscripten_async_wget2_data().

Parameters:
  • handle (int) – A handle to request to be aborted.

voidemscripten_run_preload_plugins_data(char*data,intsize,constchar*suffix,void*arg,em_run_preload_plugins_data_onload_funconload,em_arg_callback_funconerror)

Runs preload plugins on a buffer of data asynchronously. This is a “data” version ofemscripten_run_preload_plugins(), which receives raw data as input instead of a filename (this can prevent the need to write data to a file first). SeePreloading files for more information on preload plugins.

When file is loaded then theonload callback will be called. If any error occursonerror will be called.

onload also receives a second parameter, which is a ‘fake’ filename which you can pass intoIMG_Load (it is not an actual file, but it identifies this image forIMG_Load to be able to process it). Note that the user of this API is responsible forfree() ing the memory allocated for the fake filename.

Parameters:
  • data (char*) – The buffer of data to process.

  • suffix (constchar*) – The file suffix, e.g. ‘png’ or ‘jpg’.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • onload (em_run_preload_plugins_data_onload_func) –

    Callback on successful processing of the data. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

    • (const char)* : A ‘fake’ filename which you can pass intoIMG_Load. See above for more information.

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter value is:

    • (void)* : Equal toarg (user defined data).

voidemscripten_dlopen(constchar*filename,intflags,void*user_data,em_dlopen_callbackonsuccess,em_arg_callback_funconerror);

Starts an asynchronous dlopen operation to load a shared library from afilename or URL. Returns immediately and requires the caller to return to theevent loop. Theonsuccess andonerror callbacks are used to signalsuccess or failure of the request. Upononerror callback the normaldlerror C function can be used get the error details. The flags are thesame as those used in the normaldlopen C function.

Parameters:
  • filename (constchar*) – The filename (or URLs) of the shared library to load.

  • flags (int) – See dlopen flags.

  • user_data (void*) – User data passed to onsuccess, and onerror callbacks.

  • onsuccess (em_dlopen_callback) – Called if the library was loaded successfully.

  • onerror (em_arg_callback_func) – Called if there as an error loading the library.

Asynchronous IndexedDB API

IndexedDB is a browser API that lets you store data persistently, that is, you can save data there and load it later when the user re-visits the web page. IDBFS provides one way to use IndexedDB, through the Emscripten filesystem layer. Theemscripten_idb_* methods listed here provide an alternative API, directly to IndexedDB, thereby avoiding the overhead of the filesystem layer.

voidemscripten_idb_async_load(constchar*db_name,constchar*file_id,void*arg,em_async_wget_onload_funconload,em_arg_callback_funconerror)

Loads data from local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer.

When the data is ready then theonload callback will be called. If any error occurredonerror will be called.

Parameters:
  • db_name – The IndexedDB database from which to load.

  • file_id – The identifier of the data to load.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • onload (em_async_wget_onload_func) –

    Callback on successful load of the URL into the buffer. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

    • (void)* : A pointer to a buffer with the data. Note that, as with the worker API, the data buffer only lives during the callback; it must be used or copied during that time.

    • (int) : The size of the buffer, in bytes.

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

voidemscripten_idb_async_store(constchar*db_name,constchar*file_id,void*ptr,intnum,void*arg,em_arg_callback_funconstore,em_arg_callback_funconerror);

Stores data to local IndexedDB storage asynchronously. This allows use of persistent data, without the overhead of the filesystem layer.

When the data has been stored then theonstore callback will be called. If any error occurredonerror will be called.

Parameters:
  • db_name – The IndexedDB database from which to load.

  • file_id – The identifier of the data to load.

  • ptr – A pointer to the data to store.

  • num – How many bytes to store.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • onstore (em_arg_callback_func) –

    Callback on successful store of the data buffer to the URL. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

voidemscripten_idb_async_delete(constchar*db_name,constchar*file_id,void*arg,em_arg_callback_funcondelete,em_arg_callback_funconerror)

Deletes data from local IndexedDB storage asynchronously.

When the data has been deleted then theondelete callback will be called. If any error occurredonerror will be called.

Parameters:
  • db_name – The IndexedDB database.

  • file_id – The identifier of the data.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • ondelete (em_arg_callback_func) –

    Callback on successful delete

    • (void)* : Equal toarg (user defined data).

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

voidemscripten_idb_async_exists(constchar*db_name,constchar*file_id,void*arg,em_idb_exists_funconcheck,em_arg_callback_funconerror)

Checks if data with a certain ID exists in the local IndexedDB storage asynchronously.

When the data has been checked then theoncheck callback will be called. If any error occurredonerror will be called.

Parameters:
  • db_name – The IndexedDB database.

  • file_id – The identifier of the data.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • oncheck (em_idb_exists_func) –

    Callback on successful check, with arguments

    • (void)* : Equal toarg (user defined data).

    • int : Whether the file exists or not.

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter values are:

    • (void)* : Equal toarg (user defined data).

voidemscripten_idb_async_clear(constchar*db_name,void*arg,em_arg_callback_funconclear,em_arg_callback_funconerror)

Clears all data from local IndexedDB storage asynchronously.

When the storage has been cleared then theonclear callback will be called. If any error occurredonerror will be called.

Parameters:
  • db_name – The IndexedDB database.

  • arg (void*) – User-defined data that is passed to the callbacks, untouched by the API itself. This may be used by a callback to identify the associated call.

  • onclear (em_arg_callback_func) –

    Callback on successful clear. The callback function parameter is:

    • (void)* : Equal toarg (user defined data).

  • onerror (em_arg_callback_func) –

    Callback in the event of failure. The callback function parameter is:

    • (void)* : Equal toarg (user defined data).

intemscripten_run_preload_plugins(constchar*file,em_str_callback_funconload,em_str_callback_funconerror)

Runs preload plugins on a file asynchronously. It works on file data already present and performs any required asynchronous operations available as preload plugins, such as decoding images for use inIMG_Load, or decoding audio for use inMix_LoadWAV. SeePreloading files for more information on preloading plugins.

Once the operations are complete, theonload callback will be called. If any error occursonerror will be called. The callbacks are called with the file as their argument.

Parameters:
  • file (constchar*) – The name of the file to process.

  • onload (em_str_callback_func) –

    Callback on successful processing of the file. The callback function parameter value is:

    • (const char)* : The name of thefile that was processed.

  • onerror (em_str_callback_func) –

    Callback in the event of failure. The callback function parameter value is:

    • (const char)* : The name of thefile for which the operation failed.

Returns:

0 if successful, -1 if the file does not exist

Return type:

int

Compiling

EMSCRIPTEN_KEEPALIVE

Tells the compiler and linker to preserve a symbol, and export it, as if youadded it toEXPORTED_FUNCTIONS.

For example:

voidEMSCRIPTEN_KEEPALIVEmy_function(){printf("I am being kept alive\n");}

Note that this will only work if the object file in which the symbol isdefined is otherwise included by the linker. If the object file is part of anarchive, and is not otherwise referenced the linker will not include it at alland any symbols in the object file will not be included or exported. One wayto work around this limitation is to use the-Wl,--whole-archive /-Wl,--no-whole-archive flags on either side of the archive file.

Worker API

Typedefs

intworker_handle

A wrapper around web workers that lets you create workers and communicate with them.

Note that the current API is mainly focused on a main thread that sends jobs to workers and waits for responses, i.e., in an asymmetrical manner, there is no current API to send a message without being asked for it from a worker to the main thread.

typeem_worker_callback_func

Function pointer type for the callback fromemscripten_call_worker() (specific values of the parameters documented in that method).

Defined as:

typedefvoid(*em_worker_callback_func)(char*,int,void*)

Functions

worker_handleemscripten_create_worker(constchar*url)

Creates a worker.

A worker must be compiled separately from the main program, and with theBUILD_AS_WORKER flag set to 1.

That worker must not be compiled with the-pthread flag as the POSIX threads implementation and this Worker API are incompatible.

Parameters:
  • url (constchar*) – The URL of the worker script.

Returns:

A handle to the newly created worker.

Return type:

worker_handle

voidemscripten_destroy_worker(worker_handleworker)

Destroys a worker. Seeemscripten_create_worker()

Parameters:
  • worker (worker_handle) – A handle to the worker to be destroyed.

voidemscripten_call_worker(worker_handleworker,constchar*funcname,char*data,intsize,em_worker_callback_funccallback,void*arg)

Asynchronously calls a worker.

The worker function will be called with two parameters: a data pointer, and a size. The data block defined by the pointer and size exists only during the callback:it cannot be relied upon afterwards. If you need to keep some of that information outside the callback, then it needs to be copied to a safe location.

The called worker function can return data, by callingemscripten_worker_respond(). When the worker is called, if a callback was given it will be called with three arguments: a data pointer, a size, and an argument that was provided when callingemscripten_call_worker() (to more easily associate callbacks to calls). The data block defined by the data pointer and size behave like the data block in the worker function — it exists only during the callback.

Parameters:
  • worker (worker_handle) – A handle to the worker to be called.

  • funcname (constchar*) – The name of the function in the worker. The function must be a C function (so no C++ name mangling), and must be exported (EXPORTED_FUNCTIONS).

  • data (char*) – The address of a block of memory to copy over.

  • size (int) – The size of the block of memory.

  • callback (em_worker_callback_func) –

    Worker callback with the response. This can benull. The callback function parameter values are:

    • (char)* : Thedata pointer provided inemscripten_call_worker().

    • (int) : Thesize of the block of data.

    • (void)* : Equal toarg (user defined data).

  • arg (void*) – An argument (user data) to be passed to the callback

voidemscripten_worker_respond(char*data,intsize)
voidemscripten_worker_respond_provisionally(char*data,intsize)

Sends a response when in a worker call (that is, when called by the main thread usingemscripten_call_worker()).

Both functions post a message back to the thread which called the worker. Theemscripten_worker_respond_provisionally() variant can be invoked multiple times, which will queue up messages to be posted to the worker’s creator. Eventually, the _respond variant must be invoked, which will disallow further messages and free framework resources previously allocated for this worker call.

Note

Calling the provisional version is optional, but you must call the non-provisional version to avoid leaks.

Parameters:
  • data (char*) – The message to be posted.

  • size (int) – The size of the message, in bytes.

intemscripten_get_worker_queue_size(worker_handleworker)

Checks how many responses are being waited for from a worker.

This only counts calls toemscripten_call_worker() that had a callback (calls with null callbacks are ignored), and where the response has not yet been received. It is a simple way to check on the status of the worker to see how busy it is, and do basic decisions about throttling.

Parameters:
Returns:

The number of responses waited on from a worker.

Return type:

int

Logging utilities

Defines

EM_LOG_CONSOLE

If specified, logs directly to the browser console/inspector window. If not specified, logs via the application Module.

EM_LOG_WARN

If specified, prints a warning message (combined withEM_LOG_CONSOLE).

EM_LOG_INFO

If specified, prints an info message to console (combined withEM_LOG_CONSOLE).

EM_LOG_DEBUG

If specified, prints a debug message to console (combined withEM_LOG_CONSOLE).

EM_LOG_ERROR

If specified, prints an error message (combined withEM_LOG_CONSOLE). If neitherEM_LOG_WARN,EM_LOG_ERROR,EM_LOG_INFO norEM_LOG_DEBUG is specified, a log message is printed.EM_LOG_WARN,EM_LOG_INFO,EM_LOG_DEBUG andEM_LOG_ERROR are mutually exclusive. IfEM_LOG_CONSOLE is not specified then the message will be outputted via err() (forEM_LOG_ERROR orEM_LOG_WARN) or out() otherwise.

EM_LOG_C_STACK

If specified, prints a call stack that contains file names referring to original C sources using source map information.

EM_LOG_JS_STACK

If specified, prints a call stack that contains file names referring to lines in the built .js/.html file along with the message. The flagsEM_LOG_C_STACK andEM_LOG_JS_STACK can be combined to output both untranslated and translated file and line information.

EM_LOG_NO_PATHS

If specified, the pathnames of the file information in the call stack will be omitted.

Functions

longemscripten_get_compiler_setting(constchar*name)

Returns the value of a compiler setting.

For example, to return the integer representing the value ofINITIAL_MEMORY during compilation:

emscripten_get_compiler_setting("INITIAL_MEMORY")

For values containing anything other than an integer, a string is returned (you will need to cast thelong return value to achar*).

Some useful things this can do is provide the version of Emscripten (“EMSCRIPTEN_VERSION”), the optimization level (“OPT_LEVEL”), debug level (“DEBUG_LEVEL”), etc.

For this command to work, you must build with the following compiler option (as we do not want to increase the build size with this metadata):

-sRETAIN_COMPILER_SETTINGS
Parameters:
  • name (constchar*) – The compiler setting to return.

Returns:

The value of the specified setting. Note that for values other than an integer, a string is returned (cast theint return value to achar*).

Return type:

int

intemscripten_has_asyncify()

Returns whether pseudo-synchronous functions can be used.

Return type:

int

Returns:

1 if program was compiled with -sASYNCIFY, 0 otherwise.

voidemscripten_debugger()

Emitsdebugger.

This is inline in the code, which tells the JavaScript engine to invoke the debugger if it gets there.

voidemscripten_log(intflags,constchar*format,...)

Prints out a message to the console, optionally with the callstack information.

Parameters:
  • flags (int) – A binary OR of items from the list ofEM_LOG_xxx flags that specify printing options.

  • format (constchar*) – Aprintf-style format string.

  • ... – Aprintf-style “…” parameter list that is parsed according to theprintf formatting rules.

intemscripten_get_callstack(intflags,char*out,intmaxbytes)

Programmatically obtains the current callstack.

To query the amount of bytes needed for a callstack without writing it, pass 0 toout andmaxbytes, in which case the function will return the number of bytes (including the terminating zero) that will be needed to hold the full callstack. Note that this might be fully accurate since subsequent calls will carry different line numbers, so it is best to allocate a few bytes extra to be safe.

Parameters:
  • flags (int) – A binary OR of items from the list ofEM_LOG_xxx flags that specify printing options. The flagsEM_LOG_CONSOLE,EM_LOG_WARN andEM_LOG_ERROR do not apply in this function and are ignored.

  • out (char*) – A pointer to a memory region where the callstack string will be written to. The string outputted by this function will always be null-terminated.

  • maxbytes (int) – The maximum number of bytes that this function can write to the memory pointed to byout. If there is not enough space, the output will be truncated (but always null-terminated).

Returns:

The number of bytes written (not number of characters, so this will also include the terminating zero).

Return type:

int

char*emscripten_get_preloaded_image_data(constchar*path,int*w,int*h)

Gets preloaded image data and the size of the image.

The function returns pointer to loaded image or NULL — the pointer should befree()’d. The width/height of the image are written to thew andh parameters if the data is valid.

Parameters:
  • path (constchar*) – Full path/filename to the file containing the preloaded image.

  • w (int*) – Width of the image (if data is valid).

  • h (int*) – Height of the image (if data is valid).

Returns:

A pointer to the preloaded image or NULL.

Return type:

char*

char*emscripten_get_preloaded_image_data_from_FILE(FILE*file,int*w,int*h)

Gets preloaded image data from a CFILE*.

Parameters:
  • file (FILE*) – TheFILE containing the preloaded image.

  • w (int*) – Width of the image (if data is valid).

  • h (int*) – Height of the image (if data is valid).

Returns:

A pointer to the preloaded image or NULL.

Return type:

char*

intemscripten_print_double(doublex,char*to,signedmax)

Prints a double as a string, including a null terminator. This is useful because JS engines have good support for printing out a double in a way that takes the least possible size, but preserves all the information in the double, i.e., it can then be parsed back in a perfectly reversible manner (snprintf etc. do not do so, sadly).

Parameters:
  • x (double) – The double.

  • to (char*) – A pre-allocated buffer of sufficient size, or NULL if no output is requested (useful to get the necessary size).

  • max (signed) – The maximum number of bytes that can be written to the output pointer ‘to’ (including the null terminator).

Return type:

The number of necessary bytes, not including the null terminator (actually written, ifto is not NULL).

Socket event registration

The functions in this section register callback functions for receiving socket events. These events are analogous toWebSocket events but are emittedafter the internal Emscripten socket processing has occurred. This means, for example, that the message callback will be triggered after the data has been added to therecv_queue, so that an application receiving this callback can simply read the data using the file descriptor passed as a parameter to the callback. All of the callbacks are passed a file descriptor (fd) representing the socket that the notified activity took place on. The error callback also takes anint representing the socket error number (errno) and achar* that represents the error message (msg).

Only a single callback function may be registered to handle any given event, so calling a given registration function more than once will cause the first callback to be replaced. Similarly, passing aNULL callback function to anyemscripten_set_socket_*_callback call will de-register the callback registered for that event.

TheuserData pointer allows arbitrary data specified during event registration to be passed to the callback, this is particularly useful for passingthis pointers around in Object Oriented code.

In addition to being able to register network callbacks from C it is also possible for native JavaScript code to directly use the underlying mechanism used to implement the callback registration. For example, the following code shows simple logging callbacks that are registered by default whenSOCKET_DEBUG is enabled:

Module['websocket']['on']('error',function(error){console.log('Socket error '+error);});Module['websocket']['on']('open',function(fd){console.log('Socket open fd = '+fd);});Module['websocket']['on']('listen',function(fd){console.log('Socket listen fd = '+fd);});Module['websocket']['on']('connection',function(fd){console.log('Socket connection fd = '+fd);});Module['websocket']['on']('message',function(fd){console.log('Socket message fd = '+fd);});Module['websocket']['on']('close',function(fd){console.log('Socket close fd = '+fd);});

Most of the JavaScript callback functions above get passed the file descriptor of the socket that triggered the callback, the on error callback however gets passed anarray that contains the file descriptor, the error code and an error message.

Note

The underlying JavaScript implementation doesn’t passuserData. This is mostly of use to C/C++ code and theemscripten_set_socket_*_callback calls simply create a closure containing theuserData and pass that as the callback to the underlying JavaScript event registration mechanism.

Callback functions

typeem_socket_callback

Function pointer foremscripten_set_socket_open_callback(), and the other socket functions (exceptemscripten_set_socket_error_callback()). This is defined as:

typedefvoid(*em_socket_callback)(intfd,void*userData);
Param int fd:

The file descriptor of the socket that triggered the callback.

Param void* userData:

TheuserData originally passed to the event registration function.

typeem_socket_error_callback

Function pointer for theemscripten_set_socket_error_callback(), defined as:

typedefvoid(*em_socket_error_callback)(intfd,interr,constchar*msg,void*userData);
Param int fd:

The file descriptor of the socket that triggered the callback.

Param int err:

The code for the error that occurred.

Param int msg:

The message for the error that occurred.

Param void* userData:

TheuserData originally passed to the event registration function.

Functions

voidemscripten_set_socket_error_callback(void*userData,em_socket_error_callbackcallback)

Triggered by aWebSocket error.

SeeSocket event registration for more information.

Parameters:
  • userData (void*) – Arbitrary user data to be passed to the callback.

  • callback (em_socket_error_callback) – Pointer to a callback function. The callback returns a file descriptor, error code and message, and the arbitraryuserData passed to this function.

voidemscripten_set_socket_open_callback(void*userData,em_socket_callbackcallback)

Triggered when theWebSocket has opened.

SeeSocket event registration for more information.

Parameters:
  • userData (void*) – Arbitrary user data to be passed to the callback.

  • callback (em_socket_callback) – Pointer to a callback function. The callback returns a file descriptor and the arbitraryuserData passed to this function.

voidemscripten_set_socket_listen_callback(void*userData,em_socket_callbackcallback)

Triggered whenlisten has been called (synthetic event).

SeeSocket event registration for more information.

Parameters:
  • userData (void*) – Arbitrary user data to be passed to the callback.

  • callback (em_socket_callback) – Pointer to a callback function. The callback returns a file descriptor and the arbitraryuserData passed to this function.

voidemscripten_set_socket_connection_callback(void*userData,em_socket_callbackcallback)

Triggered when the connection has been established.

SeeSocket event registration for more information.

Parameters:
  • userData (void*) – Arbitrary user data to be passed to the callback.

  • callback (em_socket_callback) – Pointer to a callback function. The callback returns a file descriptor and the arbitraryuserData passed to this function.

voidemscripten_set_socket_message_callback(void*userData,em_socket_callbackcallback)

Triggered when data is available to be read from the socket.

SeeSocket event registration for more information.

Parameters:
  • userData (void*) – Arbitrary user data to be passed to the callback.

  • callback (em_socket_callback) – Pointer to a callback function. The callback returns a file descriptor and the arbitraryuserData passed to this function.

voidemscripten_set_socket_close_callback(void*userData,em_socket_callbackcallback)

Triggered when theWebSocket has closed.

SeeSocket event registration for more information.

Parameters:
  • userData (void*) – Arbitrary user data to be passed to the callback.

  • callback (em_socket_callback) – Pointer to a callback function. The callback returns a file descriptor and the arbitraryuserData passed to this function.

Unaligned types

Typedefs

typeemscripten_align1_short
typeemscripten_align2_int
typeemscripten_align1_int
typeemscripten_align2_float
typeemscripten_align1_float
typeemscripten_align4_double
typeemscripten_align2_double
typeemscripten_align1_double

Unaligned types. These may be used to force LLVM to emit unaligned loads/stores in places in your code whereSAFE_HEAP found an unaligned operation.

For usage examples seetest/core/test_set_align.c.

Note

It is better to avoid unaligned operations, but if you are reading from a packed stream of bytes or such, these types may be useful!

Pseudo-synchronous functions

These functions require Asyncify (-sASYNCIFY). These functions are asynchronous but appear synchronous in C. SeeAsyncify for more details.

Sleeping

voidemscripten_sleep(unsignedintms)

Sleep forms milliseconds. This appears to be a normal “synchronous” sleepto the code, that is, execution does not continue to the next source lineuntil the sleep is done. Note, however, that this is implemented using areturn to the event loop (it is not possible to actually sleep in a blockingmanner on the Web), which means that other async events may happen.

Network

intemscripten_wget(constchar*url,constchar*file)

Load file from url insynchronously. For the asynchronous version, see theemscripten_async_wget().

In addition to fetching the URL from the network, preload plugins are executed so that the data is usable inIMG_Load and so forth (we synchronously do the work to make the browser decode the image or audio etc.). SeePreloading files for more information on preloading files.

This function is blocking; it won’t return until all operations are finished. You can then open and read the file if it succeeded.

Parameters:
  • url (constchar*) – The URL to load.

  • file (constchar*) – The name of the file created and loaded from the URL. If the file already exists it will be overwritten. If the destination directory for the file does not exist on the filesystem, it will be created. A relative pathname may be passed, which will be interpreted relative to the current working directory at the time of the call to this function.

Returns:

0 on success or 1 on error.

voidemscripten_wget_data(constchar*url,void**pbuffer,int*pnum,int*perror);

Synchronously fetches data off the network, and stores it to a buffer in memory, which is allocated for you.You must free the buffer, or it will leak!

Parameters:
  • url – The URL to fetch from

  • pbuffer – An out parameter that will be filled with a pointer to a buffer containing the data that is downloaded. This space has been malloced for you,and you must free it, or it will leak!

  • pnum – An out parameter that will be filled with the size of the downloaded data.

  • perror – An out parameter that will be filled with a non-zero value if an error occurred.

IndexedDB

voidemscripten_idb_load(constchar*db_name,constchar*file_id,void**pbuffer,int*pnum,int*perror);

Synchronously fetches data from IndexedDB, and stores it to a buffer in memory, which is allocated for you.You must free the buffer, or it will leak!

Parameters:
  • db_name – The name of the database to load from

  • file_id – The name of the file to load

  • pbuffer – An out parameter that will be filled with a pointer to a buffer containing the data that is downloaded. This space has been malloced for you,and you must free it, or it will leak!

  • pnum – An out parameter that will be filled with the size of the downloaded data.

  • perror – An out parameter that will be filled with a non-zero value if an error occurred.

voidemscripten_idb_store(constchar*db_name,constchar*file_id,void*buffer,intnum,int*perror);

Synchronously stores data to IndexedDB.

Parameters:
  • db_name – The name of the database to store to

  • file_id – The name of the file to store

  • buffer – A pointer to the data to store

  • num – How many bytes to store

  • perror – An out parameter that will be filled with a non-zero value if an error occurred.

voidemscripten_idb_delete(constchar*db_name,constchar*file_id,int*perror);

Synchronously deletes data from IndexedDB.

Parameters:
  • db_name – The name of the database to delete from

  • file_id – The name of the file to delete

  • perror – An out parameter that will be filled with a non-zero value if an error occurred.

voidemscripten_idb_exists(constchar*db_name,constchar*file_id,int*pexists,int*perror);

Synchronously checks if a file exists in IndexedDB.

Parameters:
  • db_name – The name of the database to check in

  • file_id – The name of the file to check

  • pexists – An out parameter that will be filled with a non-zero value if the file exists in that database.

  • perror – An out parameter that will be filled with a non-zero value if an error occurred.

voidemscripten_idb_clear(constchar*db_name,int*perror);

Synchronously clears all data from IndexedDB.

Parameters:
  • db_name – The name of the database to clear

  • perror – An out parameter that will be filled with a non-zero value if an error occurred.

Asyncify functions

These functions only work when using Asyncify.

Typedefs

typeem_scan_func

Function pointer type for use in scan callbacks, receiving two pointers, forthe beginning and end of a range of memory. You can then scan that range.

Defined as:

typedefvoid(*em_scan_func)(void*,void*)

Functions

voidemscripten_scan_stack(em_scan_funcfunc)

Scan the C userspace stack, which means the stack managed by the compiledcode (as opposed to the Wasm VM’s internal stack, which is not directlyobservable). This data is already in linear memory; this function justgives you a simple way to know where it is.

voidemscripten_scan_registers(em_scan_funcfunc)

Scan “registers”, by which we mean data that is not in memory. In Wasm,that means data stored in locals, including locals in functions higher upthe stack - the Wasm VM has spilled them, but none of that is observable touser code).

Note that this function scans Wasm locals. Depending on the LLVMoptimization level, this may not scan the original locals in your sourcecode. For example in-O0 locals may be stored on the stack. To makesure you scan everything necessary, you can also doemscripten_scan_stack.

This function requires Asyncify - it relies on that option to spill thelocal state all the way up the stack. As a result, it will add overheadto your program.

ABI functions

The following functions are not declared inemscripten.h, but are usedinternally in our system libraries. You may care about them if you replace theEmscripten runtime JS code, or run Emscripten binaries in your own runtime.

voidemscripten_notify_memory_growth(i32index)

Called when memory has grown. In a JS runtime, this is used to know whento update the JS views on the Wasm memory, which otherwise we would needto constantly check for after any Wasm code runs. Seethis wasi discussion.

Parameters:
  • index (i32) – Which memory has grown.