0Pricing
WebAssembly (WASM) for High Performance Apps · Lección

Compartición de memoria y arrays tipados entre JS y WASM

Domine el intercambio eficiente de datos entre JavaScript y WebAssembly mediante memoria lineal, vistas de arrays tipados y ABI basadas en punteros.

Compartición de memoria y arrays tipados entre JS y WASM es una lección gratuita de WebAssembly (WASM) for High Performance Apps en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebAssembly (WASM) for High Performance Apps, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebAssembly (WASM) for High Performance Apps incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

The Boundary Problem

WASM functions only accept and return numbers. To pass strings, arrays, or structs you must work directly with WebAssembly.Memory — a single growable ArrayBuffer.

Linear Memory as a View

You read and write guest memory from JS by creating typed array views over the module memory buffer.

const mem = wasm.exports.memory;
const u8 = new Uint8Array(mem.buffer);
u8[0] = 65; // write a byte at offset 0

Allocating Inside WASM

The guest owns its heap, so allocate there and get back a pointer.

const ptr = wasm.exports.malloc(len);
const view = new Uint8Array(wasm.exports.memory.buffer, ptr, len);
view.set(bytes);
wasm.exports.process(ptr, len);
wasm.exports.free(ptr);

Passing Strings In

Encode a JS string to UTF-8 bytes, copy into guest memory, pass pointer + length.

const enc = new TextEncoder();
const bytes = enc.encode("hello");
const ptr = wasm.exports.malloc(bytes.length);
new Uint8Array(wasm.exports.memory.buffer, ptr, bytes.length).set(bytes);
wasm.exports.handle(ptr, bytes.length);

Reading Strings Out

Given a pointer + length returned by the guest, slice the bytes and decode.

const u8 = new Uint8Array(wasm.exports.memory.buffer, ptr, len);
const str = new TextDecoder().decode(u8);

The Detached Buffer Trap

When WASM memory grows, the old ArrayBuffer is detached and your views become invalid. Always recreate views after a call that may allocate.

Numeric Arrays

For Float64Array or Int32Array data, use the matching view and remember offsets are in bytes, so multiply the index by the element size.

const f64 = new Float64Array(wasm.exports.memory.buffer, ptr, count);

Zero-Copy with SharedArrayBuffer

If both JS and WASM use a SharedArrayBuffer-backed memory, multiple threads can read the same data without copying — powerful but requires atomics for safety.

Binding Generators

Tools like wasm-bindgen (Rust) or Emscripten embind hide this pointer arithmetic, generating glue that marshals strings and objects automatically.

Endianness & Alignment

WASM memory is little-endian. Respect type alignment (e.g. 8-byte boundaries for f64) when laying out structs manually to avoid corrupt reads.

Ownership Rules

Decide who frees what. A common convention: the side that allocates also frees. Leaking guest allocations grows linear memory until memory.grow fails.

Quick Check

Why can a typed array view become invalid after calling a WASM function?

Recap

You learned to exchange data across the boundary via linear memory, pointer + length ABIs, and typed-array views. Watch the detached-buffer trap after growth, respect alignment, define clear ownership, and lean on binding generators for ergonomics.

Preguntas frecuentes

¿La lección «Compartición de memoria y arrays tipados entre JS y WASM» es gratis?

Sí — el texto completo de «Compartición de memoria y arrays tipados entre JS y WASM» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebAssembly (WASM) for High Performance Apps, actualiza a CoddyKit PRO. El curso de WebAssembly (WASM) for High Performance Apps incluye 4 lecciones en total.

¿Qué aprenderé en «Compartición de memoria y arrays tipados entre JS y WASM»?

Domine el intercambio eficiente de datos entre JavaScript y WebAssembly mediante memoria lineal, vistas de arrays tipados y ABI basadas en punteros. Practicas WebAssembly (WASM) for High Performance Apps con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar WebAssembly (WASM) for High Performance Apps?

No se requiere experiencia previa. WebAssembly (WASM) for High Performance Apps en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Compartición de memoria y arrays tipados entre JS y WASM»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de WebAssembly (WASM) for High Performance Apps?

Sí. Cada lección de WebAssembly (WASM) for High Performance Apps incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Operaciones asíncronas con WASM
  2. Callbacks personalizados de JavaScript
  3. Gestión de errores y excepciones
  4. Compartición de memoria y arrays tipados entre JS y WASM
← Volver a WebAssembly (WASM) for High Performance Apps