2026-04-10 23:27:55 +02:00
---
layout: page
published: true
2026-04-11 00:18:36 +02:00
noToc: false
2026-04-10 23:27:55 +02:00
noComments: false
noDate: false
2026-06-14 22:16:13 +02:00
title: Embedding Fun
2026-04-10 23:27:55 +02:00
subtitle: Embedding the VM from C/Rust, lifecycle, and host integration tips.
description: Embedding the VM from C/Rust, lifecycle, and host integration tips.
permalink: /documentation/embedding/
lang: en
tags:
2026-04-11 00:18:36 +02:00
- embedding
- host
- integration
- lifecycle
- rust
- tips
2026-04-10 23:27:55 +02:00
---
2026-02-18 17:39:10 +01:00
This guide outlines how to embed the Fun VM in a host application and extend it from C/Rust.
## Overview
2026-04-15 01:25:17 +02:00
- The VM is implemented in C (see [../internals/ ](../internals/ )).
- Optional Rust-based opcodes can be enabled via `FUN_WITH_RUST` (see [../rust/ ](../rust/ )).
2026-02-18 17:39:10 +01:00
## Embedding from C
While the exact API surface may evolve, a typical embedding flow looks like:
1. Initialize the VM/runtime and allocate a context.
2. Load/compile Fun source or bytecode.
3. Push arguments or set globals as needed.
4. Execute entry function or script body.
5. Retrieve results and clean up.
2026-04-15 01:25:17 +02:00
See [https://git.xw3.org/fun/fun/src/branch/main/src/ ](https://git.xw3.org/fun/fun/src/branch/main/src/ ){:class="git"} and related headers for public entry points and value types.
2026-02-18 17:39:10 +01:00
### Hosting considerations
- Threading: share VM state cautiously or create one VM per thread.
- Memory: clarify ownership of strings/buffers crossing the boundary.
- Errors: propagate parse/runtime errors back to the host with useful messages.
## Extending with Rust
2026-04-15 01:25:17 +02:00
When `FUN_WITH_RUST=ON` , a Rust static library from [https://git.xw3.org/fun/fun/src/branch/main/src/rust ](https://git.xw3.org/fun/fun/src/branch/main/src/rust ){:class="git"} is built and linked. You can:
2026-02-18 17:39:10 +01:00
- Implement new opcodes/functions in Rust.
- Expose a C ABI for the VM to call into.
2026-04-15 01:25:17 +02:00
See [../rust/ ](../rust/ ) for details and example code.