Skip to content

Instantly share code, notes, and snippets.

@andrzejressel
Created June 1, 2024 13:22
Show Gist options
  • Save andrzejressel/e678c77f0550d5cd248142d9e7b3fa47 to your computer and use it in GitHub Desktop.
Save andrzejressel/e678c77f0550d5cd248142d9e7b3fa47 to your computer and use it in GitHub Desktop.
Java Panama Kotlin - convert list of ASCII strings
import java.lang.foreign.Arena
import java.lang.foreign.MemorySegment
import java.lang.foreign.ValueLayout.ADDRESS
import java.lang.foreign.ValueLayout.JAVA_BYTE
import java.nio.charset.StandardCharsets
fun convertToC(arena: Arena, args: List<String>): Pair<Int, MemorySegment> {
val argc = args.size
val argv = arena.allocateArray(ADDRESS, argc.toLong())
for (i in args.indices) {
val bytes = args[i].toByteArray(StandardCharsets.US_ASCII)
val stringSegment = arena.allocate((bytes.size + 1).toLong())
stringSegment.copyFrom(MemorySegment.ofArray(bytes))
stringSegment.setAtIndex(JAVA_BYTE, bytes.size.toLong(), 0.toByte()) // Null terminator
argv.setAtIndex(ADDRESS, i.toLong(), stringSegment)
}
return Pair(argc, argv)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment