Reverse C interop passing array to Kotlin Native and back

I got stuck while trying to write a library where kotlin code is called from another C library which is loaded in another application with a strict interface so I was following these tutorials to see how the interop works:

But unfortunately, there is no example for arrays which are causing trouble for me.
So I came here asking for help, since by searching the internet, I couldn’t find any such example.

This is my dummy kotlin code just to check how the data is passed around (in real scenario I would like to get the values from the C code, process them, generate a new array based on that data and then return it back):

fun myGetTest(component:COpaquePointer, valRefs:IntArray, count:Int, values:DoubleArray): IntArray 
  val myInts = intArrayOf(1, 5, 7, 13)
  return myInts

And generating the libnative_api.h I get these signatures inside:

typedef struct {
  libnative_KNativePtr pinned;
} libnative_kref_kotlin_IntArray;
typedef struct {
  libnative_KNativePtr pinned;
} libnative_kref_kotlin_DoubleArray;

libnative_kref_kotlin_IntArray (*myGetTest)(void* component, libnative_kref_kotlin_IntArray valRefs, libnative_KInt count, libnative_kref_kotlin_DoubleArray values);

And since the tutorial linked above was simple I thought everything works “magically” for all dataTypes so I naively tried this in my C code:

int main()
  libnative_ExportedSymbols* lib = libnative_symbols();
  auto c = lib->kotlin.root.myInstantiate("testName", true, true);
  auto contents = lib->kotlin.root.MyComponent.get_contents(*(libnative_kref_MyComponent*)c);
  std::cout << "Output from kotlin:\n" << contents << std::endl;

  int refs[] = {0, 1, 2};
  double vals[] = {3.14, 4.2, 7.3};
  libnative_kref_kotlin_IntArray myRefs;
  myRefs.pinned = refs;
  libnative_kref_kotlin_DoubleArray myVals;
  myVals.pinned = vals;
  auto retVal = lib->kotlin.root.myGetTest(c, myRefs, 3, myVals);

But unfortunately I keep getting garbage, both when trying to read the values passed from C to Kotlin and also when trying to read data from Kotlin in C.
Getting and reading the contents (simple string) from Component c works OK.

So I’m asking for a simple example which actually works, because I have no idea what to do with libnative_kref_kotlin_IntArray and pinned inside and how to write or read actual data.
How should the interface look on the kotlin side and how can I then fill and read the data in C and/or Kotlin?
Thank you in advance

1 Like