Comience con WebAssembly, usando solo 14 líneas de JavaScript

WebAssembly es una nueva tecnología web con un potencial enorme. Tendrá un impacto significativo en cómo se desarrollan las aplicaciones web en el futuro.

Pero, a veces, siento que simplemente no quiere que lo entiendan ... casi de una manera extrañamente pasivo-agresiva.

Cuando miro la documentación y el puñado de tutoriales que ya están disponibles, no puedo evitar sentirme como un granjero que oró por la lluvia, solo para ahogarse en una inundación. Técnicamente obtuve lo que quería ... pero no de la manera que esperaba. “¡¿Quieres lluvia ?! ¡Oh, te daré lluvia ! "

Esto se debe a que WebAssembly hace posibles tantas cosas nuevas y se puede implementar de muchas formas diferentes. Pero, ha cambiado tanto en el camino hacia su lanzamiento oficial de MVP en febrero, que cuando empiezas a aprender sobre él, es fácil ahogarte en un mar de detalles.

Continuando con la metáfora de la lluvia, este artículo es mi intento de proporcionar una ligera lluvia de introducción a WebAssembly. No los conceptos o las tuercas y tornillos, sino la implementación real.

Lo guiaré a través de los pasos para crear e implementar un proyecto extremadamente simple, eliminando la complejidad siempre que sea posible. Después de haberlo implementado una vez, aunque sea simple, muchas de esas ideas de nivel superior son mucho más fáciles de entender.

Vamos a romperlo

Todo será mucho más claro si damos un paso atrás y miramos una lista de los pasos involucrados en la implementación de WebAssembly en un proyecto.

Cuando empieza por primera vez, es fácil mirar WebAssembly y ver una gran cantidad de opciones y procesos. Dividirlo en pasos discretos nos ayudará a tener una idea clara de lo que está sucediendo:

  1. Escribir: escriba algo (o use un proyecto existente) en C, C ++ o Rust
  2. Compilar: compílelo en WebAssembly (que le proporciona un archivo .wasm binario)
  3. Incluir: obtenga ese archivo .wasm en un proyecto
  4. Crear una instancia: escriba un montón de JavaScript asincrónico que compile el binario .wasm y lo instancia en algo con lo que JS pueda jugar bien.

And that’s pretty much it. Granted, there are different permutations of this process, but that’s the gist of it.

Broadly speaking, it’s not all that complicated. However, it can get extremely complicated, because most of these steps allow for widely varying degrees of complexity. In each case, I’m going to err on the side of bare-bones simplicity.

For our project, we’ll be writing a simple function in C++ (don’t worry if you’re not familiar with C++, it’ll beextremely simple). The function will return the square of a given number.

Then, we’ll compile it into .wasm using an online tool (you won’t need to download or use any command line utilities). Next, we’ll instantiate it with 14 lines of JS.

When we’re done, you’ll be able to call a function written in C++ as if it were a JS function, and you’ll be amazed!

The sheer number of possibilities that this opens up are absolutely mind blowing.

Write

Let’s start with our C++ code. Remember, we won’t be using a local dev environment to write or compile this.

Instead, we’ll be using an online tool called WebAssembly Explorer. It’s kind of like CodePen for WebAssembly, and it allows you to compile your C or C++ code right in the browser and download a .wasm file all in one place.

Once you’ve opened up WebAssembly Explorer, type this C++ code into the leftmost window:

int squarer(int num) { return num * num;}

Like I said, we’re using a really simple example here. Even if you’ve never looked at C or C++ before, it’s probably not too difficult to tell what’s going on.

Compile

Next, click the button that says “compile” in the red bar above your C++ code. Here’s what you’ll see:

The middle column shows you a human-readable version of the .wasm binary that you’ve just created. This is called “WAT” or WebAssembly Text Format.

On the right is the resultant assembly code. Pretty cool.

I won’t go into much detail about either of these, but you do need to know at least a little bit about the WAT file in order to follow the next steps.

WAT exists because we humans generally have a hard time making sense of straight binary. It’s essentially a layer of abstraction that helps you understand and interact with your WebAssembly code.

In our case, what we want to understand is how our WebAssembly refers to the function that we just created. This because we’ll need to use that exact same name in our JS file later on to refer to it.

Any functions that you write in your C++ code will be available in WebAssembly as something called an “export.” We’ll talk a bit more about this later, but for now, all you need to know is that the exports are the things that you’ll be able to interact with and use.

Take a look at the WAT file and look for the word “export.” You’ll see it twice: once alongside the word memory and again alongside the word _Z7squareri. We don’t need to know about memory for now, but we’re definitely interested in _Z7squareri.

We used the function name squarer in our C++, but now that has somehow become _z7squareri. This can definitely be confusing the first time you see it.

As far as I can tell, the “_Z7” prefix and “i” suffix are debug markers introduced by the C++ compiler. This isn’t really important to understand in depth, though. You just need to be aware that this will happen, because you need to use this exact name in your JS file in order to call your C++ function.

Include

Now just click the “download” button at the top of the purple WAT section. You’ll get the .wasm binary file. Rename it squarer.wasm. Then create a new directory and put your squarer.wasm file in there, along with two other files:

  • index.html (boilerplate)
  • scripts.js (empty for now)

Instantiate

Now for the tricky part. Or, at least, the part that caused me a lot of confusion when I first started sifting through the documentation.

Although you’ll eventually be able to include .wasm modules like a regular old ES6 module (using