CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-julia

Julia/Python bridge with IPython support enabling seamless interoperability between Python and Julia programming languages.

Pending
Overview
Eval results
Files

low-level-api.mddocs/

Low-level LibJulia API

Direct access to Julia's C API for advanced users who need fine-grained control over the Julia runtime, memory management, and performance-critical operations. This provides the foundation for the high-level PyJulia interface.

Capabilities

LibJulia Interface Classes

Core classes providing direct access to Julia's C API functionality.

class LibJulia:
    """Low-level interface to libjulia C-API."""
    
    def __init__(self, **kwargs):
        """
        Initialize LibJulia instance.
        
        Parameters:
        - julia: Path to Julia executable
        - sysimage: Path to Julia system image
        - Various other Julia runtime options
        """

class BaseLibJulia:
    """Base class for LibJulia implementations."""

class InProcessLibJulia(BaseLibJulia):
    """LibJulia implementation for in-process Julia instances."""

LibJulia Global Management

Functions for managing the global LibJulia instance used throughout PyJulia.

def get_libjulia():
    """Get the currently active global libjulia instance."""

def set_libjulia(libjulia):
    """
    Set the global libjulia instance.
    
    Parameters:
    - libjulia: LibJulia instance to set as global
    """

def get_inprocess_libjulia(**kwargs):
    """
    Get in-process libjulia instance with options.
    
    Parameters:
    - **kwargs: Julia runtime configuration options
    
    Returns:
    - InProcessLibJulia instance
    """

LibJulia Setup and Configuration

Configure the ctypes interfaces and function signatures for libjulia.

def setup_libjulia(libjulia):
    """
    Configure libjulia ctypes interfaces and function signatures.
    
    Parameters:
    - libjulia: LibJulia instance to configure
    """

Julia Runtime Information

Access detailed information about the Julia runtime and configuration.

class JuliaInfo:
    """Container for information required to initialize Julia runtime."""
    
    def __init__(self, **kwargs):
        """
        Initialize with Julia runtime configuration.
        
        Contains information about:
        - Julia executable path
        - System image location  
        - Library paths
        - Version information
        - Compilation settings
        """

def is_compatible_exe(jl_libpython: str) -> bool:
    """
    Check if Julia executable is compatible with current Python.
    
    Parameters:
    - jl_libpython: Path to Julia's libpython
    
    Returns:
    - True if compatible, False otherwise
    """

LibPython Discovery

Find and validate libpython library paths for Julia integration.

def find_libpython():
    """
    Find all possible libpython library candidates.
    
    Returns:
    - List of potential libpython library paths
    """

def linked_libpython():
    """
    Find path to currently linked libpython library.
    
    Returns:
    - Path to linked libpython or None
    """

def library_name(name: str, suffix: str = None, is_windows: bool = None) -> str:
    """
    Generate platform-specific library name.
    
    Parameters:
    - name: Base library name
    - suffix: Platform-specific suffix (.so, .dll, .dylib)
    - is_windows: Override Windows detection
    
    Returns:
    - Platform-appropriate library filename
    """

def candidate_names(suffix: str = None) -> list:
    """Get candidate libpython library names."""

def candidate_paths(suffix: str = None) -> list:
    """Get candidate libpython library paths."""

def finding_libpython():
    """Generator yielding all libpython candidates."""

Memory Management and Type Conversion

Low-level utilities for working with Julia values and memory management.

# Supported C types for unboxing Julia values to Python
UNBOXABLE_TYPES = (
    'bool', 'int8', 'uint8', 'int16', 'uint16', 
    'int32', 'uint32', 'int64', 'uint64', 
    'float32', 'float64'
)

Platform Detection

Constants for platform-specific behavior and library handling.

# Platform detection constants
is_linux: bool    # True if running on Linux
is_windows: bool  # True if running on Windows  
is_apple: bool    # True if running on macOS

# Platform-specific shared library suffix
SHLIB_SUFFIX: str  # '.so' on Linux, '.dll' on Windows, '.dylib' on macOS

Low-level Execution Utilities

Platform-specific program execution utilities.

def execprog(cmd: list):
    """
    Execute program with platform-specific implementation.
    
    Parameters:
    - cmd: Command and arguments as list
    """

Usage Examples

Basic LibJulia Setup

from julia.libjulia import get_inprocess_libjulia, setup_libjulia

# Get a configured LibJulia instance
libjulia = get_inprocess_libjulia(
    sysimage="/path/to/custom.so",
    threads=4
)

# Set it as the global instance
from julia.libjulia import set_libjulia
set_libjulia(libjulia)

# Setup ctypes interfaces
setup_libjulia(libjulia)

Direct C API Access

from julia.libjulia import get_libjulia

# Get the current LibJulia instance
libjulia = get_libjulia()

# Access Julia C API functions directly
# (Advanced usage - requires knowledge of Julia's C API)
result = libjulia.jl_eval_string(b"2 + 3")
print(libjulia.jl_unbox_int64(result))  # 5

LibPython Discovery

from julia.find_libpython import find_libpython, linked_libpython

# Find all possible libpython paths
candidates = find_libpython()
print("LibPython candidates:", candidates)

# Get currently linked libpython
linked = linked_libpython()
print("Currently linked:", linked)

# Check specific library name format
from julia.find_libpython import library_name
lib_name = library_name("python3.9")
print("Library name:", lib_name)  # e.g., "libpython3.9.so" on Linux

Runtime Information Access

from julia.juliainfo import JuliaInfo

# Create Julia runtime info
info = JuliaInfo(
    julia="/usr/local/bin/julia",
    sysimage="/usr/local/lib/julia/sys.so"
)

# Check compatibility
from julia.juliainfo import is_compatible_exe
compatible = is_compatible_exe(info.libpython_path)
print("Compatible:", compatible)

Advanced Memory Management

from julia.libjulia import get_libjulia, UNBOXABLE_TYPES

libjulia = get_libjulia()

# Create Julia array and access raw data
jl_array = libjulia.jl_eval_string(b"[1.0, 2.0, 3.0]")

# Check if type is unboxable
print("Unboxable types:", UNBOXABLE_TYPES)

# Access array data directly (advanced usage)
# Requires careful memory management
data_ptr = libjulia.jl_array_data(jl_array)
length = libjulia.jl_array_len(jl_array)

Platform-Specific Operations

from julia.utils import is_linux, is_windows, is_apple, execprog

# Platform detection
if is_linux:
    print("Running on Linux")
elif is_windows:
    print("Running on Windows")  
elif is_apple:
    print("Running on macOS")

# Execute platform-specific commands
try:
    execprog(["julia", "--version"])
except Exception as e:
    print(f"Failed to execute: {e}")

Custom LibJulia Implementation

from julia.libjulia import BaseLibJulia, setup_libjulia

class CustomLibJulia(BaseLibJulia):
    """Custom LibJulia implementation for specialized use cases."""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # Custom initialization logic
        
    def custom_operation(self):
        """Custom low-level operation."""
        # Implementation specific to your use case
        pass

# Use custom implementation
custom_jl = CustomLibJulia()
setup_libjulia(custom_jl)

Error Handling

The low-level API provides minimal error handling - users must handle Julia exceptions and memory management carefully:

from julia.libjulia import get_libjulia

libjulia = get_libjulia()

try:
    # Direct C API calls may crash if not handled properly
    result = libjulia.jl_eval_string(b"undefined_function()")
    # Check for exceptions before using result
    if libjulia.jl_exception_occurred():
        exception = libjulia.jl_exception_in_transit()
        # Handle exception appropriately
        raise RuntimeError("Julia exception occurred")
except Exception as e:
    print(f"Low-level error: {e}")

Performance Considerations

The low-level API is designed for performance-critical applications:

  • Minimal Python overhead for Julia function calls
  • Direct memory access to Julia arrays
  • Bypasses high-level type conversion when not needed
  • Suitable for embedding Julia in performance-critical Python applications
  • Requires careful memory management to avoid crashes

Install with Tessl CLI

npx tessl i tessl/pypi-julia

docs

console-scripts.md

core-runtime.md

development-tools.md

index.md

ipython-integration.md

low-level-api.md

tile.json