ksrpcHostConnection

fun ksrpcHostConnection(env: CPointer<JNIEnvVar>, host: jobject, configure: KsrpcEnvironmentBuilder<JniSerialized>.() -> Unit = {}, setup: suspend (Connection<JniSerialized>) -> Unit)

Hosts a single ksrpc Connection inside a Kotlin/Native shared library and hands the JVM the opaque native handle that backs it.

The consumer declares the binding as an external fun on one of their own JVM classes and passes a reference to it into com.monkopedia.ksrpc.jni.KsrpcNativeHost.connect; the matching native @CName export is named after that class and delegates here:

// backs `external fun initialize(host: JniHostInit)` on
// the consumer's class `com.example.MyNativeService`:
@CName("Java_com_example_MyNativeService_initialize")
fun initialize(env: CPointer<JNIEnvVar>, clazz: jobject, host: jobject) =
ksrpcHostConnection(env, host) { conn ->
conn.registerDefault(MyServiceImpl().serialized(conn.env))
}

For each connection it builds a KsrpcEnvironment (pre-set to JniSerialization; the configure block tunes the logger, error listener, coroutine exception handler, ... and the serializer is fixed because the API is typed on JniSerialized), wraps the JVM connection object, runs setup, and returns a single native handle (a StableRef to the NativeConnection) that the JVM passes back to dispose the connection.

The setup lambda runs once per connection, on the JNI dispatcher, with the freshly-opened Connection so it can register the service(s) this connection hosts. Each connection gets its own environment and service instance(s).

Samples

import com.monkopedia.jni.JNIEnvVar
import com.monkopedia.jni.jobject
import com.monkopedia.ksrpc.channels.registerDefault
import com.monkopedia.ksrpc.jni.ksrpcHostConnection
import com.monkopedia.ksrpc.serialized
import kotlin.experimental.ExperimentalNativeApi
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi

fun main() { 
   //sampleStart 
   ksrpcHostConnection(env, host) { conn ->
        val service = object : GreetingService {
            override suspend fun greet(name: String): String = "Hello, $name!"
        }
        conn.registerDefault(service.serialized(conn.env))
    } 
   //sampleEnd
}