torsh-ffi
Foreign Function Interface for ToRSh, providing C and Python bindings.
Overview
This crate enables ToRSh to be used from other programming languages through:
- C API: Complete C bindings for all ToRSh functionality
- Python Integration: PyTorch-compatible Python API
- Language Bindings: Support for additional languages via C FFI
- Memory Safety: Safe interop with proper error handling
C API Usage
Basic Example
int
Neural Network Example
// Create a simple model
torsh_module_t* model = ;
;
;
;
// Forward pass
torsh_tensor_t* output = ;
// Create optimizer
torsh_optimizer_t* optimizer = ;
// Training step
;
;
;
Python API
Installation
# From source
# Or via pip (when available)
Basic Usage
# Tensor operations
=
=
=
# Autograd
=
= ** 2
# tensor([4.0])
# Neural networks
=
=
=
return
=
=
PyTorch Compatibility
# Convert between PyTorch and ToRSh
# PyTorch to ToRSh
=
=
# ToRSh to PyTorch
=
# Share memory (zero-copy)
=
Error Handling
C API
torsh_error_t* error = NULL;
torsh_tensor_t* result = ;
if
Python API
=
Memory Management
C API
// Reference counting
; // Increment ref count
; // Decrement ref count
// Manual memory management
void* data = ;
;
// Memory pools
torsh_memory_pool_t* pool = ; // 1MB
torsh_tensor_t* tensor = ;
; // Frees all tensors in pool
Python API
Memory is managed automatically through Python's garbage collector.
Building Language Bindings
Ruby
extend FFI::Library
ffi_lib
attach_function :torsh_init, [], :void
attach_function :torsh_tensor_from_array, [:pointer, :pointer, :int, :int], :pointer
# ... more bindings
end
Java (JNI)
Safety Considerations
- All C API functions validate inputs
- Null pointer checks on all pointer arguments
- Thread-safe operations where applicable
- Proper error propagation
- Memory leak prevention through RAII in bindings
Performance
The FFI layer adds minimal overhead:
- Zero-copy tensor creation where possible
- Efficient data transfer mechanisms
- Batched operations to reduce FFI calls
- Optional async operations
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.