Multiplatform shared library - Callback interface usage

I have a multiplatform kotlin project generating a shared library for mingwx64. Once I have generated the DLL, I have incorporated it into a C++ project and now i need to call a function that takes the implementation of an interface as a parameter, but I have no idea how to get it.

I attach example code to explain it:

//Kotlin Multiplatform code

interface InitializationEvents {
    fun onComplete()
    fun onError(error: String)
}

class MyClass {
    fun initialize(succeed: Boolean, listener: InitializationEvents) {
        if(succeed)
            listener.onComplete()
        else
            listener.onError("Error description")
    }
}

It generates a header file like this:

//libnative.h

typedef {
...
  /* User functions. */
  struct {
    struct {
      struct {
        libnative_KType* (*_type)(void);
        void (*onComplete)(libnative_kref_InitializationEvents thiz);
        void (*onError)(libnative_kref_InitializationEvents thiz, const char* error);
      } InitializationEvents;
      struct {
        libnative_KType* (*_type)(void);
        libnative_kref_MyClass (*MyClass)();
        void (*initialize)(libnative_kref_MyClass thiz, libnative_KBoolean succeed, libnative_kref_InitializationEvents listener);
      } MyClass;
    } root;
  } kotlin;
} libnative_ExportedSymbols;
extern libnative_ExportedSymbols* libnative_symbols(void);

And now Iā€™m using this Cpp code:

// Demo.cpp

int main()
{
    libnative_ExportedSymbols* lib = libnative_symbols();
    libnative_kref_MyClass myClass = lib->kotlin.root.MyClass.MyClass();

    //I guess I have to do something here... šŸ˜…
    libnative_kref_InitializationEvents listener = { .pinned = NULL };

    lib->kotlin.root.MyClass.initialize(myClass, true, listener);
}

void myOnComplete() { }

void myOnError(const char* error) { }

It would need to be able to receive the call to the myOnComplete and myOnError functions as desired by the library.

Thank you very much.

1 Like

If anyone needs help with this problem, you can find the solution in this issue:
https://youtrack.jetbrains.com/issue/KT-48147