@nyx/ffi — Cross-Language Foreign Function Interface Bridge
Zero-overhead interoperability toolkit allowing Nyx programs to call C/C++ shared libraries directly, export Python C-API acceleration extensions (PyO3 equivalent), and compile native Node.js N-API addons.
🏛️ Direct C ABI Interop
Call native system APIs, Linux libc, Windows kernel32.dll, and OpenSSL directly with extern "C".
🐍 Python Extension Generator
Write high-speed vector math or ML kernels in Nyx and import nyx_module directly in Python with NumPy buffer sharing.
🟢 Node.js / N-API Addons
Export asynchronous non-blocking native addons for Node.js, Bun, and Deno with TypeScript declaration files.
🛡️ Memory Isolation
Ensures foreign memory bounds are verified before transitioning data across foreign stack and heap boundaries.
1. Installation
# Install via Nyx Package Manager
nypm add @nyx/ffi
2. Comprehensive Practical Examples
This example implements AVX2 matrix operations in Nyx and exports them as a native Python module (nyx_math) that runs 40× faster than pure Python.
// 1. Write kernel in Nyx (math_kernel.nyx):
use @nyx/ffi;
// Function exported directly to Python runtime
pub fn dot_product(a: [f32], b: [f32]) -> f32 {
let mut sum: f32 = 0.0;
let n = a.len();
for i in 0..n {
sum += a[i] * b[i];
}
return sum;
}
pub fn apply_relu(data: mut ref [f32]) {
for i in 0..data.len() {
if data[i] < 0.0 {
data[i] = 0.0;
}
}
}
fn init() {
ffi::export_python_module("nyx_math");
}
Compile with nyxc --target=python-capi math_kernel.nyx and use directly in Python:
# 2. Use in Python (main.py):
import nyx_math
import numpy as np
# Create vectors
vec_a = [1.5, 2.0, 3.5, 4.0]
vec_b = [2.0, 0.5, 1.0, 3.0]
# Execute ultra-fast Nyx kernel
result = nyx_math.dot_product(vec_a, vec_b)
print(f"Computed Dot Product: {result}") # 19.5
Call system-level C functions (like puts, getpid, or OpenSSL cryptographic digests) with zero abstraction overhead.
use @nyx/ffi;
// Declare external C ABI function signature
extern "C" {
fn puts(s: str) -> i32;
fn getpid() -> i32;
fn sqrt(x: f64) -> f64;
}
fn main() {
let pid = getpid();
println("Current Process PID: {pid}");
let root = sqrt(144.0);
println("Square root of 144.0: {root}");
puts("Direct C ABI call executed successfully.");
}
3. Function Reference
| Signature | Parameters | Return | Description |
|---|---|---|---|
ffi::export_python_module(module_name: str) |
module_name: str |
void |
Generates Python PyModuleDef and method table exporting annotated Nyx functions as a Python C-extension. |
ffi::export_napi_module(module_name: str) |
module_name: str |
void |
Compiles Nyx functions into a Node.js N-API binary addon compatible with TypeScript and JavaScript runtimes. |
ffi::export_c_symbol(symbol: str) |
symbol: str |
FfiExport |
Exports clean unmangled C ABI entry points for consumption by external C/C++ build pipelines. |