If I want to embed a C or Obj-C file (`.h` + `.c` ...
# kotlin-native
l
If I want to embed a C or Obj-C file (
.h
+
.c
or
.m
) into a Kotlin/Native library, is setting up C-interop enough, or do I also need to do something special to export the file?
d
cinterop is enough. You may have to do more if linking is required.
l
Why would linking be required?
d
If your header is an interface into a static lib or dynamic library. Then you would need to specify this in the link lines in cinterop.
If your header file is self contained, then there's nothing more to do.
l
static lib or dynamic library means I would depend on third party dependency that is not in Apple's APIs for the Obj-C case, right? That's if I needed to use files like
.a
,
.o
,
.so
or alike?
d
Yup
"External" dependency as supposed to "Third party" dependency.
For Apple's APIs, you still have to specify this in the link-lines.
(If you're going via cinterop).
l
I'm using Foundation, to make a safe KVO (Key value observing, from
NSObject
) wrapper that unregisters on deallocation (instead of crashing the app later on subsequent value changes). Like most Apple API's, it's available straightaway from Kotlin/Native. If I use it in Obj-C that Kotlin/Native uses thanks to cinterop, I'd have to set additional configuration? How can I know what configuration need to be added?
d
There are two ways.
If you use the Kotlin/Native provided "bindings", it automatically does the linking magic. Then Obj-C code would work as expected.
It's a questionable solution, depending on what your project looks like.
The second way is to copy the config from K/N.
You pretty much want the last two lines.
👍 1
Hope that helps.
👌 1
l
I think I'll try without first. I'll then learn if specifying them is really needed.
d
Sweet. Report back when you get it working!
m
If your C code is relatively simple - it can be placed directly to
.def
file, like this: https://github.com/JetBrains/kotlin-native/blob/master/performance/cinterop/src/nativeInterop/cinterop/struct.def
l
In my case, it's Obj-C code. I'll see how long it ends up, but given my experience with that awful syntax (IMHO, at the very least), it'll be as short as possible, so I'll probably try that as well.
I didn't end up adding Obj-C directly into the
.def
file because I had 3 files (that I wrote in AppCode) and prefered to keep them that way and allow syntactic coloration on GitHub. I succeeded into making custom Obj-C source code interop with Kotlin, but I ended up putting this aside for other reason detailed in the commit message if you're curious. https://github.com/LouisCAD/Splitties/commit/daaa98e5de78a2cd831096b780bdd283d23ba47e Thanks for the help, was interesting to learn about, despite me not falling in love with Obj-C 😅