From 19461d814372cac2efddf1011bc4c20e35b87849 Mon Sep 17 00:00:00 2001 From: Igor Chevdar Date: Thu, 31 Aug 2017 15:33:11 +0300 Subject: [PATCH] Removed/cached some reflection calls --- .../kotlin/kotlinx/cinterop/JvmNativeMem.kt | 5 +++++ .../jvm/kotlin/kotlinx/cinterop/JvmTypes.kt | 19 ++++++++++--------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmNativeMem.kt b/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmNativeMem.kt index a4fbb1f979d..74a1012494e 100644 --- a/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmNativeMem.kt +++ b/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmNativeMem.kt @@ -91,6 +91,11 @@ object nativeMemUtils { fun zeroMemory(dest: NativePointed, length: Int): Unit = unsafe.setMemory(dest.address, length.toLong(), 0) + @Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE") + inline fun allocateInstance(): T { + return unsafe.allocateInstance(T::class.java) as T + } + internal class NativeAllocated(rawPtr: NativePtr) : NativePointed(rawPtr) fun alloc(size: Long, align: Int): NativePointed { diff --git a/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmTypes.kt b/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmTypes.kt index 1a09af359b4..2d821df1d81 100644 --- a/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmTypes.kt +++ b/Interop/Runtime/src/jvm/kotlin/kotlinx/cinterop/JvmTypes.kt @@ -16,32 +16,33 @@ package kotlinx.cinterop +import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.full.companionObjectInstance -import kotlin.reflect.full.primaryConstructor typealias NativePtr = Long val nativeNullPtr: NativePtr = 0L // TODO: the functions below should eventually be intrinsified -inline fun typeOf() = T::class.companionObjectInstance as CVariable.Type +private val typeOfCache = ConcurrentHashMap, CVariable.Type>() + +@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE") +inline fun typeOf() = + typeOfCache.computeIfAbsent(T::class.java) { T::class.companionObjectInstance as CVariable.Type } /** * Returns interpretation of entity with given pointer, or `null` if it is null. * * @param T must not be abstract */ +@Suppress("NON_PUBLIC_CALL_FROM_PUBLIC_INLINE") inline fun interpretNullablePointed(ptr: NativePtr): T? { if (ptr == nativeNullPtr) { return null } else { - val kClass = T::class - val primaryConstructor = kClass.primaryConstructor - if (primaryConstructor == null) { - throw IllegalArgumentException("${kClass.simpleName} doesn't have a constructor") - } - @Suppress("UNCHECKED_CAST") - return (primaryConstructor as (NativePtr) -> T)(ptr) + val result = nativeMemUtils.allocateInstance() + result.rawPtr = ptr + return result } }