JavaCPP bindings for CPython 3.13.5 enabling Java applications to embed Python interpreters and interact with Python objects through the Python C API
npx @tessl/cli install tessl/maven-org-bytedeco--cpython@3.13.00
# CPython JavaCPP Bindings
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: org.bytedeco:cpython
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Version**: 3.13.5-1.5.12
10
- **Installation**: Add Maven dependency `org.bytedeco:cpython:3.13.5-1.5.12`
11
12
## Core Imports
13
14
```java
15
import static org.bytedeco.cpython.global.python.*;
16
import org.bytedeco.cpython.helper.python;
17
import org.bytedeco.cpython.*;
18
```
19
20
## Basic Usage
21
22
```java
23
import static org.bytedeco.cpython.global.python.*;
24
import org.bytedeco.cpython.helper.python;
25
26
// Initialize Python interpreter
27
python.Py_Initialize();
28
29
// Create and manipulate Python objects
30
PyObject list = PyList_New(0);
31
PyObject item = PyUnicode_FromString("Hello from Java!");
32
PyList_Append(list, item);
33
34
// Execute Python code
35
PyRun_SimpleString("print('Python embedded in Java!')");
36
37
// Clean up
38
Py_Finalize();
39
```
40
41
## Architecture
42
43
The CPython JavaCPP bindings are organized around several key components:
44
45
- **Global Functions** (`org.bytedeco.cpython.global.python`): Direct bindings to Python C API functions
46
- **Helper Utilities** (`org.bytedeco.cpython.helper.python`): Convenience methods for common operations
47
- **Object Types**: Complete set of Python object type representations (PyObject, PyListObject, etc.)
48
- **Memory Management**: Direct access to Python's memory allocation and garbage collection
49
- **Exception System**: Full Python exception handling from Java
50
- **Thread Safety**: GIL (Global Interpreter Lock) management for multi-threaded applications
51
52
## Capabilities
53
54
### Python Interpreter Initialization
55
56
Core functionality for setting up and configuring Python interpreters within Java applications. Essential for all Python embedding scenarios.
57
58
```java { .api }
59
// Basic initialization
60
public static native void Py_Initialize();
61
public static native void Py_InitializeEx(int initsigs);
62
public static native void Py_Finalize();
63
64
// Configuration-based initialization
65
public static native PyStatus Py_InitializeFromConfig(PyConfig config);
66
public static native void PyConfig_InitPythonConfig(PyConfig config);
67
```
68
69
[Initialization](./initialization.md)
70
71
### Python Object Operations
72
73
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.
74
75
```java { .api }
76
// Core object operations
77
public static native long Py_REFCNT(PyObject ob);
78
public static native PyTypeObject Py_TYPE(PyObject ob);
79
public static native int Py_Is(PyObject x, PyObject y);
80
81
// List operations
82
public static native PyObject PyList_New(long size);
83
public static native int PyList_Append(PyObject list, PyObject item);
84
public static native PyObject PyList_GetItem(PyObject list, long index);
85
86
// Dictionary operations
87
public static native PyObject PyDict_New();
88
public static native int PyDict_SetItem(PyObject dict, PyObject key, PyObject item);
89
public static native PyObject PyDict_GetItem(PyObject dict, PyObject key);
90
91
// String operations
92
public static native PyObject PyUnicode_FromString(String str);
93
public static native long PyUnicode_GetLength(PyObject unicode);
94
95
// Numeric operations
96
public static native PyObject PyLong_FromLong(long value);
97
public static native long PyLong_AsLong(PyObject obj);
98
public static native PyObject PyFloat_FromDouble(double value);
99
public static native double PyFloat_AsDouble(PyObject obj);
100
101
// Tuple operations
102
public static native PyObject PyTuple_New(@Cast("Py_ssize_t") long size);
103
public static native PyObject PyTuple_GetItem(PyObject tuple, @Cast("Py_ssize_t") long index);
104
public static native int PyTuple_SetItem(PyObject tuple, @Cast("Py_ssize_t") long index, PyObject item);
105
```
106
107
[Objects](./objects.md)
108
109
### Memory Management
110
111
Direct access to Python's memory allocation system and garbage collection. Critical for applications that need fine-grained control over memory usage.
112
113
```java { .api }
114
// Raw memory allocation
115
public static native Pointer PyMem_RawMalloc(long size);
116
public static native void PyMem_RawFree(Pointer ptr);
117
118
// Python memory allocation (with GIL)
119
public static native Pointer PyMem_Malloc(long size);
120
public static native void PyMem_Free(Pointer ptr);
121
122
// Object allocation
123
public static native PyObject PyType_GenericAlloc(PyTypeObject type, long nitems);
124
```
125
126
[Memory Management](./memory-management.md)
127
128
### Exception Handling
129
130
Complete Python exception system integration allowing Java applications to handle Python errors and set Python exceptions from Java code.
131
132
```java { .api }
133
// Exception state management
134
public static native PyObject PyErr_Occurred();
135
public static native void PyErr_Clear();
136
137
// Setting exceptions
138
public static native void PyErr_SetString(PyObject exception, String message);
139
public static native void PyErr_SetObject(PyObject exception, PyObject value);
140
141
// Exception fetch/restore
142
public static native void PyErr_Fetch(PointerPointer type, PointerPointer value, PointerPointer traceback);
143
public static native void PyErr_Restore(PyObject type, PyObject value, PyObject traceback);
144
145
// Built-in exception types
146
public static native PyObject PyExc_ValueError();
147
public static native PyObject PyExc_TypeError();
148
public static native PyObject PyExc_RuntimeError();
149
```
150
151
[Exceptions](./exceptions.md)
152
153
### Module and Import System
154
155
Python module loading, creation, and import system access. Enables Java applications to work with Python modules and packages.
156
157
```java { .api }
158
// Module creation and management
159
public static native PyObject PyModule_New(String name);
160
public static native PyObject PyModule_GetDict(PyObject module);
161
public static native int PyModule_AddObject(PyObject module, String name, PyObject value);
162
163
// Import system
164
public static native PyObject PyImport_ImportModule(String name);
165
public static native PyObject PyImport_ImportModuleLevel(String name, PyObject globals, PyObject locals, PyObject fromlist, int level);
166
```
167
168
[Modules](./modules.md)
169
170
### Utility Functions and Helpers
171
172
Additional utilities including code execution and evaluation, buffer protocol, callable objects, threading, and type system operations.
173
174
```java { .api }
175
// Code execution and evaluation
176
public static native int PyRun_SimpleString(String command);
177
public static native PyObject PyRun_String(String str, int start, PyObject globals, PyObject locals);
178
public static native PyObject Py_CompileString(String str, String filename, int start);
179
public static native PyObject PyEval_EvalCode(PyObject code, PyObject globals, PyObject locals);
180
181
// Callable operations
182
public static native int PyCallable_Check(PyObject obj);
183
public static native PyObject PyObject_Call(PyObject callable, PyObject args, PyObject kwargs);
184
185
// Threading and GIL
186
public static native @Cast("PyGILState_STATE") int PyGILState_Ensure();
187
public static native void PyGILState_Release(@Cast("PyGILState_STATE") int state);
188
189
// Type system
190
public static native int PyType_Ready(PyTypeObject type);
191
public static native int PyObject_IsInstance(PyObject obj, PyObject cls);
192
```
193
194
[Utilities](./utilities.md)
195
196
## Key Types
197
198
```java { .api }
199
// Base object types
200
class PyObject extends Pointer { }
201
class PyVarObject extends PyObject { }
202
class PyTypeObject extends PyVarObject { }
203
204
// Container types
205
class PyListObject extends PyVarObject { }
206
class PyDictObject extends PyObject { }
207
class PyTupleObject extends PyVarObject { }
208
209
// String types
210
class PyUnicodeObject extends PyObject { }
211
class PyBytesObject extends PyVarObject { }
212
213
// Configuration types
214
class PyConfig extends Pointer { }
215
class PyStatus extends Pointer { }
216
class PyInterpreterConfig extends Pointer { }
217
218
// Threading types
219
class PyThreadState extends Pointer { }
220
```
221
222
## Important Notes
223
224
### Thread Safety and GIL
225
226
Python's Global Interpreter Lock (GIL) must be properly managed when calling Python C API functions from multiple Java threads:
227
228
```java
229
// Acquire GIL before Python operations
230
int gilState = PyGILState_Ensure();
231
try {
232
// Python API calls here
233
PyObject result = PyRun_SimpleString("print('Hello')");
234
} finally {
235
// Always release GIL
236
PyGILState_Release(gilState);
237
}
238
```
239
240
### Memory Management
241
242
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.
243
244
### Error Handling
245
246
Always check for Python exceptions after calling Python C API functions:
247
248
```java
249
PyObject result = PyList_New(10);
250
if (PyErr_Occurred() != null) {
251
// Handle the exception
252
PyErr_Clear();
253
}
254
```
255
256
### Platform Support
257
258
The bindings include precompiled native libraries for Windows, macOS, and Linux platforms, with automatic platform detection and loading.