Hey, can anyone point me to some info on how to pa...
# kotlin-native
a
Hey, can anyone point me to some info on how to pass variadic args to a c function?
k
look at the generated kotlin binding. what type is the parameter?
a
the binding says:
Copy code
vararg variadicArguments: kotlin.Any?
I'm trying to wrap calls to snprintf in a kotlin actual function
k
then you should be able to call it like any variadic function
a
I can call it with hard-coded values, but I'm having difficulty figuring out how to wrap the kotlin
Copy code
vararg args: Any?
that comes from the wrapping function
alternatively, any suggestions on how to emulate java's String.format() in K/N would be most welcome! :-)
Hmmm, I appear to have found the answer to my question - you can't do that: http://c-faq.com/varargs/handoff.html
n
Have you tried using the printf function ( https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html ) from the POSIX library?
a
Yeah, so the problem is that I'm trying to forward from a vararg kotlin function (my expect function) to a C function that takes variadic args. Turns out that this is impossible.
My google searches have turned up a fair bit of into on how impossible this is: http://c-faq.com/varargs/wacky.html
So it appears that a String.format function for kotlin common is not as simple as just calling printf and living with the differences.
k
so I just added a random call to
printf
in my
iosMain
source set, and the IDE doesn't seem to have any problem with it
a
It is the forwarding of the variadic args in C that is the hard bit
calling printf with a fixed number of args is straightforward
also, in IOS, you're using objective-c, aren't you?
(I know nothing about IOS)
k
Copy code
fun somefun(vararg args: Any) {
    printf("", args)
}
a
I believe that passes the array as a single arg
When you execute the code, it will come back with this:
Copy code
type kotlin.Array<out kotlin.Any?>  is not supported here: doesn't correspond to any C type
My code it running on linux, btw - although the snprintf function that I'm using is posix, so exists most places
k
i see what you mean. I am certain there's a way to do this, but i don't have time to dig through the cinterop types ATM.
a
Don't worry - I'm pretty sure there isn't actually a way; it's a limitation of C. Thanks for your help! 🙂
Others have solve this in the C world with things like dyncall and libffi (which used to be part of K/N) but these are all non-portable.
Who new something so simple could be so difficult?