Skip to content

Commit f6968e5

Browse files
committed
docs: Add External Function Registration section to zyntax_embed README
Include examples for: - Registering extern "C" functions with with_symbols() - Declaring extern functions in Zyntax code - Supported type mappings table - Working with length-prefixed strings
1 parent e58200b commit f6968e5

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

crates/zyntax_embed/README.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,58 @@ runtime.add_import_resolver(Box::new(|module_path| {
321321
runtime.add_filesystem_resolver("./src", "zig");
322322
```
323323

324+
## External Function Registration
325+
326+
Register Rust functions directly with the runtime:
327+
328+
```rust
329+
// Define extern "C" functions
330+
extern "C" fn native_add(a: i32, b: i32) -> i32 { a + b }
331+
extern "C" fn native_print(x: i32) { println!("{}", x); }
332+
333+
// Register at construction
334+
let symbols: &[(&str, *const u8)] = &[
335+
("native_add", native_add as *const u8),
336+
("native_print", native_print as *const u8),
337+
];
338+
let mut runtime = ZyntaxRuntime::with_symbols(symbols)?;
339+
340+
// Use from Zyntax code
341+
runtime.compile_with_grammar(&grammar, r#"
342+
extern fn native_add(a: i32, b: i32) i32;
343+
extern fn native_print(x: i32) void;
344+
345+
pub fn main() i32 {
346+
const result = native_add(10, 32);
347+
native_print(result);
348+
return result;
349+
}
350+
"#)?;
351+
```
352+
353+
### Supported Types
354+
355+
| Rust Type | Zyntax Type |
356+
|-----------|-------------|
357+
| `i32`, `i64` | `i32`, `i64` |
358+
| `f32`, `f64` | `f32`, `f64` |
359+
| `bool` | `bool` |
360+
| `*const u8` | `[]const u8` (string pointer) |
361+
| `*mut T` | `*T` (mutable pointer) |
362+
363+
### Working with Strings
364+
365+
```rust
366+
extern "C" fn print_string(ptr: *const u8) {
367+
unsafe {
368+
let len = *(ptr as *const i32) as usize;
369+
let data = ptr.add(4);
370+
let bytes = std::slice::from_raw_parts(data, len);
371+
println!("{}", std::str::from_utf8(bytes).unwrap_or(""));
372+
}
373+
}
374+
```
375+
324376
## ZRTL Plugin Loading
325377

326378
Load native runtime libraries:

0 commit comments

Comments
 (0)