Java Native Access (JNA) provides Java programs easy access to native shared libraries without writing anything but Java code - no JNI or native code is required.
npx @tessl/cli install tessl/maven-net-java-dev-jna--jna@4.5.00
# Java Native Access (JNA) 4.5.2
1
2
Java Native Access (JNA) provides Java programs easy access to native shared libraries without writing anything but Java code - no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes.
3
4
## Installation
5
6
```java { .api }
7
// Maven dependency
8
<dependency>
9
<groupId>net.java.dev.jna</groupId>
10
<artifactId>jna</artifactId>
11
<version>4.5.2</version>
12
</dependency>
13
```
14
15
## Core Imports
16
17
```java { .api }
18
import com.sun.jna.*;
19
import com.sun.jna.ptr.*;
20
import com.sun.jna.win32.*;
21
22
// Core classes
23
import com.sun.jna.Native;
24
import com.sun.jna.Library;
25
import com.sun.jna.Pointer;
26
import com.sun.jna.Memory;
27
import com.sun.jna.Structure;
28
import com.sun.jna.Function;
29
import com.sun.jna.NativeLibrary;
30
```
31
32
## Basic Usage Example
33
34
```java { .api }
35
import com.sun.jna.*;
36
37
// Define library interface
38
public interface CLibrary extends Library {
39
CLibrary INSTANCE = Native.loadLibrary("c", CLibrary.class);
40
41
/**
42
* Print formatted string to stdout
43
* @param format Format string
44
* @param args Arguments for format string
45
* @return Number of characters written
46
*/
47
int printf(String format, Object... args);
48
49
/**
50
* Get length of string
51
* @param s Null-terminated string
52
* @return Length of string
53
*/
54
int strlen(String s);
55
}
56
57
// Usage
58
CLibrary.INSTANCE.printf("Hello World\n");
59
int len = CLibrary.INSTANCE.strlen("Hello");
60
```
61
62
## Architecture Overview
63
64
JNA is organized into several key components that work together to provide seamless Java-to-native interoperability:
65
66
### Core Library Loading & Native Functions
67
- **Native** - Central class for loading libraries and accessing native functionality
68
- **Library** - Interface for defining native library mappings
69
- **Function** - Represents pointers to native functions with invocation capabilities
70
- **NativeLibrary** - Manages native library resources and function lookup
71
72
### Memory Management & Pointers
73
- **Pointer** - Base class for native memory access with type-safe operations
74
- **Memory** - Heap-allocated native memory with automatic cleanup
75
- **PointerType** - Base for custom pointer-based types
76
77
### Structures & Type Mapping
78
- **Structure** - Maps Java classes to C structs with automatic memory layout
79
- **Union** - Represents C unions where fields share memory location
80
- **TypeMapper** - Custom type conversion between Java and native types
81
- **NativeMapped** - Interface for objects that can be converted to native types
82
83
### Platform & Utilities
84
- **Platform** - Cross-platform detection and information
85
- **WString** - Wide character string support for Unicode
86
- **IntegerType/NativeLong** - Platform-specific integer types
87
88
## Key Capabilities
89
90
### 1. Core Library Loading & Native Functions
91
92
Load native libraries and call functions with automatic type conversion:
93
94
```java { .api }
95
// Load library by name
96
MyLibrary lib = Native.loadLibrary("mylib", MyLibrary.class);
97
98
// Get native library instance for advanced usage
99
NativeLibrary nativeLib = NativeLibrary.getInstance("mylib");
100
Function func = nativeLib.getFunction("my_function");
101
102
// Direct function invocation
103
Object result = func.invoke(String.class, new Object[]{"arg1", 42});
104
```
105
106
**[→ See Memory Management Documentation](memory-management.md)**
107
108
### 2. Memory Management & Pointers
109
110
Safely allocate and access native memory:
111
112
```java { .api }
113
// Allocate native memory
114
Memory buffer = new Memory(1024);
115
116
// Type-safe memory access
117
buffer.setInt(0, 42);
118
buffer.setString(4, "Hello", "UTF-8");
119
120
int value = buffer.getInt(0);
121
String text = buffer.getString(4, "UTF-8");
122
123
// Pointer arithmetic and sharing
124
Pointer shared = buffer.share(100, 200); // Offset 100, size 200
125
```
126
127
**[→ See Memory Management Documentation](memory-management.md)**
128
129
### 3. Structures & Type Mapping
130
131
Map Java classes to native structures:
132
133
```java { .api }
134
public static class Point extends Structure {
135
public int x, y;
136
137
public Point() { super(); }
138
public Point(int x, int y) {
139
this.x = x;
140
this.y = y;
141
write(); // Write fields to native memory
142
}
143
144
@Override
145
protected List<String> getFieldOrder() {
146
return Arrays.asList("x", "y");
147
}
148
}
149
150
// Usage
151
Point p = new Point(10, 20);
152
someNativeFunction(p); // Pass by reference
153
p.read(); // Read updated values from native memory
154
```
155
156
**[→ See Structures & Types Documentation](structures-types.md)**
157
158
### 4. Pass-by-Reference Parameters
159
160
Handle native functions that modify parameters using ByReference classes:
161
162
```java { .api }
163
import com.sun.jna.ptr.*;
164
165
// Native function: int divide(int dividend, int divisor, int* quotient, int* remainder)
166
public interface MathLibrary extends Library {
167
MathLibrary INSTANCE = Native.loadLibrary("mathlib", MathLibrary.class);
168
169
int divide(int dividend, int divisor,
170
IntByReference quotient, IntByReference remainder);
171
}
172
173
// Usage
174
IntByReference quotient = new IntByReference();
175
IntByReference remainder = new IntByReference();
176
177
int result = MathLibrary.INSTANCE.divide(17, 5, quotient, remainder);
178
if (result == 0) {
179
System.out.println("17 ÷ 5 = " + quotient.getValue() + " remainder " + remainder.getValue());
180
}
181
182
// Available reference types: IntByReference, LongByReference, ByteByReference,
183
// ShortByReference, FloatByReference, DoubleByReference, PointerByReference, etc.
184
```
185
186
**[→ See Pointer References Documentation](ptr-package.md)**
187
188
### 5. Windows Integration
189
190
Windows-specific functionality with stdcall support:
191
192
```java { .api }
193
import com.sun.jna.win32.StdCallLibrary;
194
import com.sun.jna.win32.W32APIOptions;
195
196
public interface Kernel32 extends StdCallLibrary {
197
Kernel32 INSTANCE = Native.loadLibrary("kernel32", Kernel32.class,
198
W32APIOptions.DEFAULT_OPTIONS);
199
200
/**
201
* Get current process ID
202
* @return Current process ID
203
*/
204
int GetCurrentProcessId();
205
206
/**
207
* Get handle to current process
208
* @return Handle to current process
209
*/
210
Pointer GetCurrentProcess();
211
}
212
```
213
214
**[→ See Windows Integration Documentation](windows.md)**
215
216
## Native Class - Central Functionality
217
218
The `Native` class provides the core functionality for loading libraries and accessing native operations:
219
220
```java { .api }
221
/**
222
* Load a native library and create a Java interface proxy
223
* @param name Library name (without extension)
224
* @param interfaceClass Interface extending Library
225
* @return Proxy instance implementing the interface
226
*/
227
public static <T extends Library> T loadLibrary(String name, Class<T> interfaceClass);
228
229
/**
230
* Load library with custom options
231
* @param name Library name
232
* @param interfaceClass Interface class
233
* @param options Map of library options
234
* @return Proxy instance
235
*/
236
public static <T extends Library> T loadLibrary(String name, Class<T> interfaceClass,
237
Map<String, ?> options);
238
239
/**
240
* Allocate native memory
241
* @param size Number of bytes to allocate
242
* @return Pointer to allocated memory
243
*/
244
public static long malloc(long size);
245
246
/**
247
* Free native memory
248
* @param ptr Pointer returned by malloc
249
*/
250
public static void free(long ptr);
251
252
// Constants
253
public static final int POINTER_SIZE; // Size of native pointer (4 or 8 bytes)
254
public static final int WCHAR_SIZE; // Size of wide character
255
public static final boolean DEBUG_LOAD; // Debug library loading
256
public static final boolean DEBUG_JNI; // Debug JNI operations
257
```
258
259
## Library Interface - Define Native Mappings
260
261
```java { .api }
262
/**
263
* Base interface for all native library mappings
264
*/
265
public interface Library {
266
// Library options for customization
267
String OPTION_TYPE_MAPPER = "type-mapper";
268
String OPTION_FUNCTION_MAPPER = "function-mapper";
269
String OPTION_INVOCATION_MAPPER = "invocation-mapper";
270
String OPTION_STRUCTURE_ALIGNMENT = "structure-alignment";
271
String OPTION_STRING_ENCODING = "string-encoding";
272
String OPTION_ALLOW_OBJECTS = "allow-objects";
273
String OPTION_CALLING_CONVENTION = "calling-convention";
274
String OPTION_CLASSLOADER = "classloader";
275
String OPTION_OPEN_FLAGS = "open-flags";
276
}
277
```
278
279
## Platform Detection
280
281
```java { .api }
282
/**
283
* Platform information and detection utilities
284
*/
285
public final class Platform {
286
// OS Type constants
287
public static final int MAC = 0;
288
public static final int LINUX = 1;
289
public static final int WINDOWS = 2;
290
public static final int SOLARIS = 3;
291
public static final int FREEBSD = 4;
292
public static final int OPENBSD = 5;
293
public static final int WINDOWSCE = 6;
294
public static final int AIX = 7;
295
public static final int ANDROID = 8;
296
public static final int GNU = 9;
297
public static final int KFREEBSD = 10;
298
public static final int NETBSD = 11;
299
300
// Current platform info
301
public static final String ARCH; // Current architecture
302
public static final String C_LIBRARY_NAME; // Standard C library name
303
public static final String MATH_LIBRARY_NAME; // Math library name
304
305
// Feature detection
306
public static final boolean HAS_AWT; // AWT support available
307
public static final boolean HAS_BUFFERS; // NIO Buffer support
308
public static final boolean HAS_JAWT; // Java AWT Native Interface
309
public static final boolean HAS_DLL_CALLBACKS; // DLL callback support
310
311
/**
312
* Get current OS type constant
313
* @return OS type constant (MAC, LINUX, WINDOWS, etc.)
314
*/
315
public static int getOSType();
316
317
/**
318
* Check if running on macOS
319
* @return true if macOS
320
*/
321
public static boolean isMac();
322
323
/**
324
* Check if running on Linux
325
* @return true if Linux
326
*/
327
public static boolean isLinux();
328
329
/**
330
* Check if running on Windows
331
* @return true if Windows
332
*/
333
public static boolean isWindows();
334
335
/**
336
* Check if running on Android
337
* @return true if Android
338
*/
339
public static boolean isAndroid();
340
341
/**
342
* Check if 64-bit platform
343
* @return true if 64-bit
344
*/
345
public static boolean is64Bit();
346
347
/**
348
* Check if Intel/x86 architecture
349
* @return true if Intel architecture
350
*/
351
public static boolean isIntel();
352
353
/**
354
* Check if PowerPC architecture
355
* @return true if PowerPC
356
*/
357
public static boolean isPPC();
358
359
/**
360
* Check if ARM architecture
361
* @return true if ARM
362
*/
363
public static boolean isARM();
364
}
365
```
366
367
## Error Handling
368
369
```java { .api }
370
/**
371
* Exception thrown when native function returns error code
372
*/
373
public class LastErrorException extends RuntimeException {
374
/**
375
* Create exception with message
376
* @param msg Error message
377
*/
378
public LastErrorException(String msg);
379
380
/**
381
* Create exception with error code
382
* @param code Native error code (errno or GetLastError)
383
*/
384
public LastErrorException(int code);
385
386
/**
387
* Get the native error code
388
* @return Error code from errno or GetLastError
389
*/
390
public int getErrorCode();
391
}
392
```
393
394
## Usage Patterns
395
396
### Simple Library Interface
397
398
```java { .api }
399
// Define interface
400
public interface MathLibrary extends Library {
401
MathLibrary INSTANCE = Native.loadLibrary("m", MathLibrary.class);
402
403
double sin(double x);
404
double cos(double x);
405
double sqrt(double x);
406
}
407
408
// Use library
409
double result = MathLibrary.INSTANCE.sin(Math.PI / 2);
410
```
411
412
### Library with Options
413
414
```java { .api }
415
Map<String, Object> options = new HashMap<>();
416
options.put(Library.OPTION_STRING_ENCODING, "UTF-8");
417
options.put(Library.OPTION_STRUCTURE_ALIGNMENT, Structure.ALIGN_DEFAULT);
418
419
MyLibrary lib = Native.loadLibrary("mylib", MyLibrary.class, options);
420
```
421
422
### Function Pointer Usage
423
424
```java { .api }
425
// Get function pointer from library
426
NativeLibrary lib = NativeLibrary.getInstance("mylib");
427
Function func = lib.getFunction("callback_setter");
428
429
// Create callback
430
Callback cb = new Callback() {
431
public int callback(int value) {
432
return value * 2;
433
}
434
};
435
436
// Pass callback to native function
437
func.invoke(Void.class, new Object[]{cb});
438
```
439
440
## Function Class - Direct Native Function Access
441
442
The `Function` class provides direct access to native function pointers with flexible invocation capabilities:
443
444
```java { .api }
445
/**
446
* Represents a pointer to a native function with invocation methods
447
*/
448
public class Function extends Pointer {
449
// Call convention constants
450
public static final int C_CONVENTION = 0; // Standard C calling convention
451
public static final int ALT_CONVENTION = 0x3F; // Alternate convention (stdcall)
452
public static final int THROW_LAST_ERROR = 0x40; // Throw exception on error
453
public static final int USE_VARARGS = 0x180; // Enable varargs support
454
public static final int MAX_NARGS = 256; // Maximum argument count
455
456
/**
457
* Get function from library by name (C convention)
458
* @param libraryName Library containing the function
459
* @param functionName Name of the function
460
* @return Function instance
461
*/
462
public static Function getFunction(String libraryName, String functionName);
463
464
/**
465
* Get function with specific calling convention
466
* @param libraryName Library containing the function
467
* @param functionName Name of the function
468
* @param callFlags Calling convention and options
469
* @return Function instance
470
*/
471
public static Function getFunction(String libraryName, String functionName, int callFlags);
472
473
/**
474
* Get function with encoding
475
* @param libraryName Library containing the function
476
* @param functionName Name of the function
477
* @param callFlags Calling convention and options
478
* @param encoding String encoding for parameters
479
* @return Function instance
480
*/
481
public static Function getFunction(String libraryName, String functionName,
482
int callFlags, String encoding);
483
484
/**
485
* Get function from native pointer address
486
* @param functionAddress Native address of function
487
* @return Function instance
488
*/
489
public static Function getFunction(Pointer functionAddress);
490
491
/**
492
* Get function from native pointer with options
493
* @param functionAddress Native address of function
494
* @param callFlags Calling convention and options
495
* @return Function instance
496
*/
497
public static Function getFunction(Pointer functionAddress, int callFlags);
498
499
/**
500
* Invoke function with return type and arguments
501
* @param returnType Expected return type
502
* @param args Function arguments
503
* @return Result converted to return type
504
*/
505
public Object invoke(Class<?> returnType, Object[] args);
506
507
/**
508
* Invoke function with options
509
* @param returnType Expected return type
510
* @param args Function arguments
511
* @param options Invocation options
512
* @return Result converted to return type
513
*/
514
public Object invoke(Class<?> returnType, Object[] args, Map<String, ?> options);
515
516
/**
517
* Invoke using reflection method information
518
* @param method Method providing signature information
519
* @param parameterTypes Expected parameter types
520
* @param returnType Expected return type
521
* @param args Function arguments
522
* @param options Invocation options
523
* @return Result converted to return type
524
*/
525
public Object invoke(Method method, Class<?>[] parameterTypes, Class<?> returnType,
526
Object[] args, Map<String, ?> options);
527
528
/**
529
* Get function name
530
* @return Function name or address string
531
*/
532
public String getName();
533
534
/**
535
* Get calling convention flags
536
* @return Calling convention and option flags
537
*/
538
public int getCallingConvention();
539
540
// Type-specific invocation methods
541
public void invokeVoid(Object[] args);
542
public int invokeInt(Object[] args);
543
public long invokeLong(Object[] args);
544
public float invokeFloat(Object[] args);
545
public double invokeDouble(Object[] args);
546
public Pointer invokePointer(Object[] args);
547
public String invokeString(Object[] args);
548
}
549
```
550
551
### Function Usage Examples
552
553
```java
554
// Direct function access with different return types
555
Function strlen = Function.getFunction("c", "strlen");
556
int length = (Integer) strlen.invoke(Integer.class, new Object[]{"Hello"});
557
558
Function malloc = Function.getFunction("c", "malloc");
559
Pointer memory = (Pointer) malloc.invoke(Pointer.class, new Object[]{1024L});
560
561
Function free = Function.getFunction("c", "free");
562
free.invoke(Void.class, new Object[]{memory});
563
564
// Windows stdcall function
565
Function messageBox = Function.getFunction("user32", "MessageBoxA", Function.ALT_CONVENTION);
566
int result = (Integer) messageBox.invoke(Integer.class,
567
new Object[]{Pointer.NULL, "Hello World", "Title", 0});
568
569
// Function with error checking
570
Function openFile = Function.getFunction("kernel32", "CreateFileA",
571
Function.ALT_CONVENTION | Function.THROW_LAST_ERROR);
572
try {
573
Pointer handle = (Pointer) openFile.invoke(Pointer.class,
574
new Object[]{"test.txt", 0x40000000, 0, null, 3, 0, null});
575
} catch (LastErrorException e) {
576
System.err.println("Failed to open file: " + e.getMessage());
577
}
578
```
579
580
## Sub-Documentation
581
582
- **[Memory Management](memory-management.md)** - Detailed memory allocation, pointer operations, and memory safety
583
- **[Structures & Types](structures-types.md)** - Structure mapping, unions, type conversion, and callbacks
584
- **[Pointer References (ptr Package)](ptr-package.md)** - Pass-by-reference parameters and ByReference classes
585
- **[Windows Integration](windows.md)** - Windows-specific functionality, stdcall support, and Win32 APIs
586
587
## Version Information
588
589
```java { .api }
590
// JNA version constants (internal)
591
String JNA_VERSION = "4.5.2"; // Library version
592
String NATIVE_VERSION = "5.0.1"; // Native library version
593
```
594
595
This documentation provides comprehensive coverage of JNA's API for seamless Java-to-native interoperability without requiring JNI knowledge or native code development.