Created
June 1, 2024 13:22
-
-
Save andrzejressel/e678c77f0550d5cd248142d9e7b3fa47 to your computer and use it in GitHub Desktop.
Java Panama Kotlin - convert list of ASCII strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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