I'm looking for a way to use a CoAP lib on iOS in ...
# kotlin-native
t
I'm looking for a way to use a CoAP lib on iOS in my Kotlin/Native code. I found a C library (https://github.com/obgm/libcoap) which does what I need. I don't have a lot of experience with C so this is quite new for me. Could anyone tell me if it would be possible to use this library in Kotlin on iOS using cinterop?
d
Yes this is possible.
t
The library has instructions to build it using ./configure and make. Is that needed as well if I want to use cinterop or can I skip those instructions? Do I just need to copy the c files to my project and create a .def file?
d
They are a couple ways but I'll give the idiomatic way.
You'll need to run
./configue
and
make
to get the static/dynamic libraries.
The headers alone will give you intellisense in the IDE but you'll need the
.a
,
.dynlib
or
.framework
to run.
t
@Dominaezzz thanks, I appreciate your help. I created a def file for cinterop and that enabled autocompletion. Now I still need to get the compilation working. The library is not specifically made for iOS. I’m not sure if that would cause any problems. Won’t
./configure
build it for the machine the command is run from? Would the built framework work on iOS as well? I executed both commands and it gave me a
.a
and
.dynlib
file. How can I tell cinterop where it can find these files?
d
I don't know enough about iOS to say it will work but I'm pretty sure.
You'll need to add
linkerOpts = -L/path/to/files -lcoap
. Assuming the file look like
libcoap.a
.
You can specify
linkerOpts
via gradle or cinterop. For your use case I recommend going via gradle.
If you give me a snippet of your gradle build script,
Copy code
iosArm32() {
/// This bit here
}
I can show you.
t
@Dominaezzz This is the Gradle code I currently have for the iOS target:
Copy code
val libcoap by main.cinterops.creating {
    val path = "src/nativeInterop/cinterop/libcoap"

    defFile("$path/libcoap.def")

    val headerFiles = arrayOf("libcoap.h", "async.h", "subscribe.h", "coap_dtls.h")
        .map { "$path/$it" }
        .toTypedArray()
    headers = project.files(*headerFiles)
}
d
You should probably specify the headers in the def file and just specify the includeDirectory in gradle.
t
@Dominaezzz Thanks I was able to get it to work by defining the linkerOpts in the def file. Now I am able to compile the code for iOS. Thank you very much for your help! Next step for me is to try to use this library in Kotlin, which probably will get a bit challenging as I’m still very new to C.
d
Feel free to ask any questions.
memScoped
is your friend 🙂.