can kotlin-native give me the name of the binary a...
# kotlin-native
n
can kotlin-native give me the name of the binary as part of the args in main.. ? i want to use clikt and give the main command the name of the binary so that error and help messages will be correct no matter what the executable was renamed to..
b
I don't think that's even possible in native world in general.
You can do it in bash, though, so for unix platforms you could append your binary to a bash script that would invoke it and pass the name as a regular argument
It's for jvm, but the same strategy should work for any executable
n
i found a code snippet that does this on linux:
Copy code
/** Returns the path to the executing binary. */
val fullBinaryPath: String by lazy {
    memScoped {
        val length = PATH_MAX.toULong()
        val pathBuf = allocArray<ByteVar>(length.toInt())
        val myPid = getpid()
        val res = readlink("/proc/$myPid/exe", pathBuf, length)
        if (res < 1)
            throw RuntimeException("/proc/$myPid/exe failed: $res")

        pathBuf.toKString()
    }
}
and i use it like so:
Copy code
class MyCommand(binary: String) : CliktCommand(
    name = fullBinaryPath.substringAfterLast("/"),
    invokeWithoutSubcommand = false
) {
...
}

fun main(vararg args: String) {
    ...
    
    MyCommand().main(args)
}
b
Neat!
A long way about it but hey, as long as it works, right? 😀
r
I don't think that's even possible in native world in general.
Pretty sure
argv[0]
is the running executable in a C program. Apparently other mechanisms are platform specific - see https://stackoverflow.com/a/9098478/1423361
n
@Rob Elliot yes in C that is the case, but kotlin decided to use the jvm main semantics instead and hides that info it does make multiplatform code easier.. because we do not have to strip of the first arg.. but tbh.. i do ot understand why they did that
r
Yes, I was replying to Martynas (quoted). Can kotlin native have multiple platform specific implementations of a method, so that you can bind to different platform calls on glibc / BSD / whatever?