-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibC.java
More file actions
62 lines (52 loc) · 1.85 KB
/
LibC.java
File metadata and controls
62 lines (52 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main;
import static java.lang.foreign.ValueLayout.*;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
class LibC {
private final Arena allocator;
Linker linker = Linker.nativeLinker();
SymbolLookup lib = linker.defaultLookup();
MemorySegment fopenAddress = lib.find("fopen").orElseThrow();
// FILE *fopen(const char *filename, const char *mode)
FunctionDescriptor fopenDesc = FunctionDescriptor.of(ADDRESS, ADDRESS, ADDRESS);
MethodHandle fopen = linker.downcallHandle(fopenAddress, fopenDesc);
//char *fgets(char *str, int n, FILE *stream)
MemorySegment fgetsAddress = lib.find("fgets").orElseThrow();
FunctionDescriptor fgetsDesc =
FunctionDescriptor.of(ADDRESS, ADDRESS, JAVA_INT, ADDRESS);
MethodHandle fgets = linker.downcallHandle(fgetsAddress, fgetsDesc);
//int fclose(FILE *stream)
MemorySegment fcloseAddress = lib.find("fclose").orElseThrow();
FunctionDescriptor fcloseDesc =
FunctionDescriptor.of(JAVA_INT, ADDRESS);
MethodHandle fclose = linker.downcallHandle(fcloseAddress, fcloseDesc);
LibC(Arena arena) {
this.allocator = arena;
}
MemorySegment fopen(String filePath, String mode) {
MemorySegment pathPtr = allocator.allocateFrom(filePath);
MemorySegment modePtr = allocator.allocateFrom(mode);
try {
return (MemorySegment) fopen.invoke(pathPtr, modePtr);
}
catch (Throwable e) {
return MemorySegment.NULL;
}
}
MemorySegment fgets(MemorySegment buffer, int size, MemorySegment filePtr) {
try {
return (MemorySegment) fgets.invoke(buffer, size, filePtr);
}
catch (Throwable e) {
return MemorySegment.NULL;
}
}
int fclose(MemorySegment filePtr) {
try {
return (int) fclose.invoke(filePtr);
}
catch (Throwable e) {
return -1;
}
}
}