or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

exceptions.mdindex.mdinitialization.mdmemory-management.mdmodules.mdobjects.mdutilities.md
tile.json

tessl/maven-org-bytedeco--cpython

JavaCPP bindings for CPython 3.13.5 enabling Java applications to embed Python interpreters and interact with Python objects through the Python C API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.bytedeco/cpython@3.13.x

To install, run

npx @tessl/cli install tessl/maven-org-bytedeco--cpython@3.13.0

index.mddocs/

CPython JavaCPP Bindings

JavaCPP bindings for CPython 3.13.5 that enable Java applications to embed Python interpreters and interact directly with Python objects through the Python C API. This library provides comprehensive access to Python's runtime from Java, including object creation, manipulation, memory management, exception handling, and module loading.

Package Information

  • Package Name: org.bytedeco:cpython
  • Package Type: maven
  • Language: Java
  • Version: 3.13.5-1.5.12
  • Installation: Add Maven dependency org.bytedeco:cpython:3.13.5-1.5.12

Core Imports

import static org.bytedeco.cpython.global.python.*;
import org.bytedeco.cpython.helper.python;
import org.bytedeco.cpython.*;

Basic Usage

import static org.bytedeco.cpython.global.python.*;
import org.bytedeco.cpython.helper.python;

// Initialize Python interpreter
python.Py_Initialize();

// Create and manipulate Python objects
PyObject list = PyList_New(0);
PyObject item = PyUnicode_FromString("Hello from Java!");
PyList_Append(list, item);

// Execute Python code
PyRun_SimpleString("print('Python embedded in Java!')");

// Clean up
Py_Finalize();

Architecture

The CPython JavaCPP bindings are organized around several key components:

  • Global Functions (org.bytedeco.cpython.global.python): Direct bindings to Python C API functions
  • Helper Utilities (org.bytedeco.cpython.helper.python): Convenience methods for common operations
  • Object Types: Complete set of Python object type representations (PyObject, PyListObject, etc.)
  • Memory Management: Direct access to Python's memory allocation and garbage collection
  • Exception System: Full Python exception handling from Java
  • Thread Safety: GIL (Global Interpreter Lock) management for multi-threaded applications

Capabilities

Python Interpreter Initialization

Core functionality for setting up and configuring Python interpreters within Java applications. Essential for all Python embedding scenarios.

// Basic initialization
public static native void Py_Initialize();
public static native void Py_InitializeEx(int initsigs);
public static native void Py_Finalize();

// Configuration-based initialization
public static native PyStatus Py_InitializeFromConfig(PyConfig config);
public static native void PyConfig_InitPythonConfig(PyConfig config);

Initialization

Python Object Operations

Comprehensive API for creating, manipulating, and managing Python objects from Java. Covers all major Python types including lists, dictionaries, strings, numeric types (integers, floats), tuples, and custom objects.

// Core object operations
public static native long Py_REFCNT(PyObject ob);
public static native PyTypeObject Py_TYPE(PyObject ob);
public static native int Py_Is(PyObject x, PyObject y);

// List operations
public static native PyObject PyList_New(long size);
public static native int PyList_Append(PyObject list, PyObject item);
public static native PyObject PyList_GetItem(PyObject list, long index);

// Dictionary operations
public static native PyObject PyDict_New();
public static native int PyDict_SetItem(PyObject dict, PyObject key, PyObject item);
public static native PyObject PyDict_GetItem(PyObject dict, PyObject key);

// String operations
public static native PyObject PyUnicode_FromString(String str);
public static native long PyUnicode_GetLength(PyObject unicode);

// Numeric operations
public static native PyObject PyLong_FromLong(long value);
public static native long PyLong_AsLong(PyObject obj);
public static native PyObject PyFloat_FromDouble(double value);
public static native double PyFloat_AsDouble(PyObject obj);

// Tuple operations
public static native PyObject PyTuple_New(@Cast("Py_ssize_t") long size);
public static native PyObject PyTuple_GetItem(PyObject tuple, @Cast("Py_ssize_t") long index);
public static native int PyTuple_SetItem(PyObject tuple, @Cast("Py_ssize_t") long index, PyObject item);

Objects

Memory Management

Direct access to Python's memory allocation system and garbage collection. Critical for applications that need fine-grained control over memory usage.

// Raw memory allocation
public static native Pointer PyMem_RawMalloc(long size);
public static native void PyMem_RawFree(Pointer ptr);

// Python memory allocation (with GIL)
public static native Pointer PyMem_Malloc(long size);
public static native void PyMem_Free(Pointer ptr);

// Object allocation
public static native PyObject PyType_GenericAlloc(PyTypeObject type, long nitems);

Memory Management

Exception Handling

Complete Python exception system integration allowing Java applications to handle Python errors and set Python exceptions from Java code.

// Exception state management
public static native PyObject PyErr_Occurred();
public static native void PyErr_Clear();

// Setting exceptions
public static native void PyErr_SetString(PyObject exception, String message);
public static native void PyErr_SetObject(PyObject exception, PyObject value);

// Exception fetch/restore
public static native void PyErr_Fetch(PointerPointer type, PointerPointer value, PointerPointer traceback);
public static native void PyErr_Restore(PyObject type, PyObject value, PyObject traceback);

// Built-in exception types
public static native PyObject PyExc_ValueError();
public static native PyObject PyExc_TypeError();
public static native PyObject PyExc_RuntimeError();

Exceptions

Module and Import System

Python module loading, creation, and import system access. Enables Java applications to work with Python modules and packages.

// Module creation and management
public static native PyObject PyModule_New(String name);
public static native PyObject PyModule_GetDict(PyObject module);
public static native int PyModule_AddObject(PyObject module, String name, PyObject value);

// Import system
public static native PyObject PyImport_ImportModule(String name);
public static native PyObject PyImport_ImportModuleLevel(String name, PyObject globals, PyObject locals, PyObject fromlist, int level);

Modules

Utility Functions and Helpers

Additional utilities including code execution and evaluation, buffer protocol, callable objects, threading, and type system operations.

// Code execution and evaluation
public static native int PyRun_SimpleString(String command);
public static native PyObject PyRun_String(String str, int start, PyObject globals, PyObject locals);
public static native PyObject Py_CompileString(String str, String filename, int start);
public static native PyObject PyEval_EvalCode(PyObject code, PyObject globals, PyObject locals);

// Callable operations
public static native int PyCallable_Check(PyObject obj);
public static native PyObject PyObject_Call(PyObject callable, PyObject args, PyObject kwargs);

// Threading and GIL
public static native @Cast("PyGILState_STATE") int PyGILState_Ensure();
public static native void PyGILState_Release(@Cast("PyGILState_STATE") int state);

// Type system
public static native int PyType_Ready(PyTypeObject type);
public static native int PyObject_IsInstance(PyObject obj, PyObject cls);

Utilities

Key Types

// Base object types
class PyObject extends Pointer { }
class PyVarObject extends PyObject { }
class PyTypeObject extends PyVarObject { }

// Container types
class PyListObject extends PyVarObject { }
class PyDictObject extends PyObject { }
class PyTupleObject extends PyVarObject { }

// String types
class PyUnicodeObject extends PyObject { }
class PyBytesObject extends PyVarObject { }

// Configuration types  
class PyConfig extends Pointer { }
class PyStatus extends Pointer { }
class PyInterpreterConfig extends Pointer { }

// Threading types
class PyThreadState extends Pointer { }

Important Notes

Thread Safety and GIL

Python's Global Interpreter Lock (GIL) must be properly managed when calling Python C API functions from multiple Java threads:

// Acquire GIL before Python operations
int gilState = PyGILState_Ensure();
try {
    // Python API calls here
    PyObject result = PyRun_SimpleString("print('Hello')");
} finally {
    // Always release GIL
    PyGILState_Release(gilState);
}

Memory Management

Most Python C API functions return new references that must be properly managed. The JavaCPP framework handles native memory cleanup, but understanding Python's reference counting is important for avoiding memory leaks.

Error Handling

Always check for Python exceptions after calling Python C API functions:

PyObject result = PyList_New(10);
if (PyErr_Occurred() != null) {
    // Handle the exception
    PyErr_Clear();
}

Platform Support

The bindings include precompiled native libraries for Windows, macOS, and Linux platforms, with automatic platform detection and loading.