How to correctly return the Kotlin class to the callback С++?

There is a shared addin library and a main program written in C++.

Header addin.h:

class IAddIn {
public:
    virtual const char* Test()= 0;
};

library:

#include "addin.h"

class AddIn : IAddIn {
public:
    const char* Test() {
        return "libC test ok";
    }

};

int GetClassObject(IAddIn** pInterface)
{
    if (!*pInterface)
    {
        *pInterface = (IAddIn*) new AddIn();
        //return (long)*pInterface;
    }

    return 0;
}

main:

#include "addin.h"
#include <stdio.h>
#include <windows.h>

// DLL function signature
typedef int (*_getClassObject)(void*);
int TestAddIn(const char* dllname);

int main(){
    int errC = TestAddIn("addinC.dll");
    return errC;
}

int TestAddIn(const char* dllname){

    _getClassObject GetClassObject;
    HINSTANCE hinstLib;

    // Load DLL file
    hinstLib = LoadLibrary(TEXT(dllname));
    if (hinstLib == NULL) {
        printf("ERROR: unable to load DLL %s\n", dllname);
        return 1;
    }
    // Get function pointer
    GetClassObject = (_getClassObject)GetProcAddress(hinstLib, "GetClassObject");
    if (GetClassObject == NULL) {
        printf("ERROR: unable to find DLL function GetClassObject\n");
        FreeLibrary(hinstLib);
        return 1;
    }

    IAddIn* addin = 0;

    GetClassObject(&addin);
    const char* testStr = addin->Test();
    puts(testStr);

    return 0;
}

Main programm load shared library and call Test function. Then I want to rewrite the library in Kotlin.

lib.kt:

import kotlinx.cinterop.*

class AddInClass{
    fun Test():String{
        return "Kotlin test ok"
    }
}

@CName("GetClassObject")
fun GetClassObject(pInterface: COpaquePointerVar): Int
{
    val adding = AddInClass()
    val stableRef = StableRef.create(adding)
    pInterface.value = stableRef.asCPointer()

    return 0
}

but the Test function is not called. Memory access error.

How is Kotlin class stored in memory? How to make it stored in memory just like a C ++ class for passing to a callback?

GitHub repo: GitHub - ITmind/KotlinNativeCAddOnExample: KotlinNative C AddOn Example

Kotlin does not support C++ interop. There is no way for Kotlin to inherit from C++ classes or even use them (unless they are nothing more than C-compatible POD types). If you want to mix C++ and Kotlin, you need to define a C API through which they can communicate.

1 Like