Saltar al contenido

Exportar Funciones

En esta página

El decorador @export marca una función para ser expuesta como símbolo público del módulo wasm. Con el modo --aot --host browser, el compilador genera:

  • 03-export.wasm — el módulo compilado
  • 03-export.js — wrappers JS tipados para cada función @export
  • 03-export.d.ts — declaraciones TypeScript correspondientes

Desde el lado JS/TS, el uso resulta natural:

import init, { fib, greet, even } from './03-export.js';
await init(); // instancia el módulo
fib(10); // 55
greet('Zolo'); // "Hello, Zolo!"
even(4); // true

Tipos en la frontera (MVP): intnumber, boolboolean, strstring, y retorno void. Las cadenas cruzan la frontera mediante glue generado (el loader escribe la cadena JS en la memoria wasm y lee el resultado de vuelta); int y bool cruzan directamente. Cualquier otro tipo en una función @export (float, arrays, structs) falla la compilación con E_WasmAotUnsupportedFeature.

El código de nivel superior sigue ejecutándose en zolo_main() — llámalo desde JS si necesitas el efecto de inicialización:

Tres funciones @export con tipos de frontera escalares: int, str y bool.

03-export.zolo
Playground
// Feature: export Zolo functions to JS/TS — `@export` (AOT wasm)

// Syntax: `@export fn name(args) -> T { ... }`

// When to use: build a Zolo library that JavaScript/TypeScript calls directly.

//

// Build (AOT, browser):

//   zolo build 32-webassembly/03-export.zolo --emit wasm --host browser --aot \

//     -o 32-webassembly/target/03-export.wasm

//   # -> 03-export.wasm + 03-export.js (typed wrappers) + 03-export.d.ts

//

// Then from JS/TS:

//   import init, { fib, greet, even } from "./03-export.js"

//   await init()              // instantiate the module

//   fib(10)                   // 55

//   greet("Zolo")             // "Hello, Zolo!"

//   even(4)                   // true

//

// Boundary types (MVP): int <-> number, bool <-> boolean, str <-> string,

// and a void return. Anything else on an @export (float, arrays, structs)

// fails the build with E_WasmAotUnsupportedFeature. Strings cross via the

// generated glue (it writes the JS string into wasm memory and reads results

// back); int/bool cross directly. `print` still goes to the console.


@export
fn fib(n: int) -> int {
  if n < 2 { return n }
  return fib(n - 1) + fib(n - 2)
}

@export
fn greet(name: str) -> str {
  return "Hello, {name}!"
}

@export
fn even(n: int) -> bool {
  return n % 2 == 0
}

// Top-level code still runs on `zolo_main()` (call it from JS if you want it).

"03-export loaded" |> print()

// expected (run natively): 03-export loaded

Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.

Desafío

Añade una cuarta función @export fn square(n: int) -> int que retorne n * n. Recompila y confirma que aparece en el .d.ts generado.

Buscar en Zolo

9 resultados

enespt-br