Compartilhando Memória e Matrizes Tipadas entre JS e WASM
Domine a troca eficiente de dados entre JavaScript e WebAssembly usando memória linear, visões de matrizes tipadas e ABIs baseadas em ponteiros.
Compartilhando Memória e Matrizes Tipadas entre JS e WASM é uma aula grátis de WebAssembly (WASM) for High Performance Apps no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de WebAssembly (WASM) for High Performance Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de WebAssembly (WASM) for High Performance Apps inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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 0Allocating 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.
Perguntas Frequentes
A aula “Compartilhando Memória e Matrizes Tipadas entre JS e WASM” é grátis?
Sim — o texto completo de “Compartilhando Memória e Matrizes Tipadas entre JS e WASM” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de WebAssembly (WASM) for High Performance Apps, atualize para CoddyKit PRO. O curso de WebAssembly (WASM) for High Performance Apps inclui 4 aulas no total.
O que vou aprender em “Compartilhando Memória e Matrizes Tipadas entre JS e WASM”?
Domine a troca eficiente de dados entre JavaScript e WebAssembly usando memória linear, visões de matrizes tipadas e ABIs baseadas em ponteiros. Você pratica WebAssembly (WASM) for High Performance Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar WebAssembly (WASM) for High Performance Apps?
Nenhuma experiência prévia é necessária. WebAssembly (WASM) for High Performance Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Compartilhando Memória e Matrizes Tipadas entre JS e WASM”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de WebAssembly (WASM) for High Performance Apps?
Sim. Cada aula de WebAssembly (WASM) for High Performance Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Operações assíncronas com WASM
- Callbacks personalizados de JavaScript
- Tratamento de erros e exceções
- Compartilhando Memória e Matrizes Tipadas entre JS e WASM