Skip to content

Commit 8cb407e

Browse files
committed
Free the memory the Swift runtime allocated in swift_getTypeName().
1 parent 7dd04a5 commit 8cb407e

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

JavaSwiftKitDemo/src/main/java/org/swift/javakit/SwiftKit.java

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,36 @@ static MemorySegment findOrThrow(String symbol) {
6363
.orElseThrow(() -> new UnsatisfiedLinkError("unresolved symbol: %s".formatted(symbol)));
6464
}
6565

66+
// ==== ------------------------------------------------------------------------------------------------------------
67+
// free
68+
/**
69+
* Descriptor for the free C runtime function.
70+
*/
71+
public static final FunctionDescriptor free$descriptor = FunctionDescriptor.ofVoid(
72+
ValueLayout.ADDRESS
73+
);
74+
75+
/**
76+
* Address of the free C runtime function.
77+
*/
78+
public static final MemorySegment free$addr = findOrThrow("free");
79+
80+
/**
81+
* Handle for the free C runtime function.
82+
*/
83+
public static final MethodHandle free$handle = Linker.nativeLinker().downcallHandle(free$addr, free$descriptor);
84+
85+
/**
86+
* free the given pointer
87+
*/
88+
public static void cFree(MemorySegment pointer) {
89+
try {
90+
free$handle.invokeExact(pointer);
91+
} catch (Throwable ex$) {
92+
throw new AssertionError("should not reach here", ex$);
93+
}
94+
}
95+
6696
// ==== ------------------------------------------------------------------------------------------------------------
6797
// swift_retainCount
6898

@@ -383,7 +413,9 @@ public static String nameOfSwiftType(MemorySegment typeMetadata, boolean qualifi
383413
try (Arena arena = Arena.ofConfined()) {
384414
MemorySegment charsAndLength = (MemorySegment)swift_getTypeName$handle.invokeExact((SegmentAllocator)arena, typeMetadata, qualified);
385415
MemorySegment utf8Chars = charsAndLength.get(SWIFT_POINTER, 0);
386-
return utf8Chars.getString(0);
416+
String typeName = utf8Chars.getString(0);
417+
cFree(utf8Chars);
418+
return typeName;
387419
}
388420
} catch (Throwable ex$) {
389421
throw new AssertionError("should not reach here", ex$);

0 commit comments

Comments
 (0)