Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run an interactive program compiled with Emscripten in a web page?

I've got a simple program, say the following:

#include <stdio.h>

int main()
{
    char buf[100];
    while (fgets(buf, sizeof(buf), stdin) != NULL) {
        printf("You typed: %s", buf);
    }
}

and I have compiled it using Emscripten:

emcc -o hello.html hello.cpp

This gives me a pretty basic Emscripten-generated web page that contains a simple window for program output. However, the fgets() call causes a browser popup window, presumably from prompt(). I can type things, and the results eventually get shown in the output window. This is not an ideal interactive experience.

What I would like is a more conventional "console" interface, where the user can type interactively in the terminal window to supply input to the interactive program.

I suspect the solution may lie in something like JQueryTerminal, Hyper, or Xterm.js, but I am so far unclear on how to actually connect any of those to an Emscripten-compiled program.

How can I provide a "console" interface to my Emscripten code?

like image 587
Greg Hewgill Avatar asked Jan 17 '18 01:01

Greg Hewgill


People also ask

How do you run Emscripten?

On Windows open the Emscripten Command Prompt, a command prompt that has been pre-configured with the correct system paths and settings to point to the active Emscripten tools. To access this prompt, type Emscripten in the Windows 8 start screen, and then select the Emscripten Command Prompt option.

Can you use C with JavaScript?

It is possible to implement a C API in JavaScript! This is the approach used in many of Emscripten's libraries, like SDL1 and OpenGL. You can use it to write your own APIs to call from C/C++.

What is EMCC compiler?

The Emscripten Compiler Frontend ( emcc ) is used to call the Emscripten compiler from the command line. It is effectively a drop-in replacement for a standard compiler like gcc or clang.


1 Answers

It's not exactly what you wanted, I think that is not possible, but here is Prof of Concept of Async code, it abuse fetch API in C and use Proxy in JavaScript for XHR that handle messages from C. You can extend it to have any async code that need to be done in JS. The example use jQuery Terminal and it behave exactly as your example C code.

https://gist.github.com/jcubic/87f2b4c5ef567be43796e179ca08c0da

I've also created an issue about async code in emscripten repo

EDIT: Someone was able to compile R programming language to WebAssemly with this approach: https://github.com/georgestagg/webR

like image 148
jcubic Avatar answered Oct 08 '22 18:10

jcubic