From 20d95ae4c81bd7ec1e939ffb966b3fd464dd4c29 Mon Sep 17 00:00:00 2001 From: Svyatoslav Scherbina Date: Mon, 17 Apr 2017 16:24:14 +0300 Subject: [PATCH] Implement methods for conversions between Long and CPointer --- INTEROP.md | 10 ++++++++++ .../Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt | 4 ++++ .../src/native/kotlin/kotlinx/cinterop/Varargs.kt | 4 ++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/INTEROP.md b/INTEROP.md index 5634c5ee058..259d8256848 100644 --- a/INTEROP.md +++ b/INTEROP.md @@ -151,6 +151,16 @@ val intPtr: CPointer = bytePtr.reinterpret() As in C, those reinterpret casts are unsafe and could potentially lead to subtle memory problems in an application. +Also there are unsafe casts between `CPointer?` and `Long` available, +provided by `.toLong()` and `.toCPointer()` extension methods: +``` +val longValue = ptr.toLong() +val originalPtr = longValue.toCPointer() +``` + +Note that if the type of the result is known from the context, the type argument +can be omitted as usual due to type inference. + ### Memory allocation ### The native memory can be allocated using `NativePlacement` interface, e.g. diff --git a/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt b/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt index e57499ff797..ff9b742e17b 100644 --- a/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt +++ b/Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt @@ -161,6 +161,10 @@ val CPointer<*>?.rawValue: NativePtr fun CPointer<*>.reinterpret(): CPointer = interpretCPointer(this.rawValue)!! +fun CPointer?.toLong() = this.rawValue.toLong() + +fun Long.toCPointer(): CPointer? = interpretCPointer(nativeNullPtr + this) + /** * The [CPointed] without any specified interpretation. */ diff --git a/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Varargs.kt b/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Varargs.kt index 15ae7ec28df..271e4866c48 100644 --- a/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Varargs.kt +++ b/Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Varargs.kt @@ -78,7 +78,7 @@ fun callWithVarargs(codePtr: NativePtr, returnValuePtr: NativePtr, returnTypeKin // All supported arguments take at most 8 bytes each: val argumentsStorage = argumentsPlacement.allocArray(totalArgumentsNumber) val arguments = argumentsPlacement.allocArray>(totalArgumentsNumber) - val types = argumentsPlacement.allocArray>(totalArgumentsNumber) + val types = argumentsPlacement.allocArray(totalArgumentsNumber) var index = 0 @@ -87,7 +87,7 @@ fun callWithVarargs(codePtr: NativePtr, returnValuePtr: NativePtr, returnTypeKin val typeKind = convertArgument(argument, isVariadic = isVariadic, location = storage, additionalPlacement = argumentsPlacement) - types[index] = interpretCPointer(nativeNullPtr + typeKind.toLong()) + types[index] = typeKind.toLong().toCPointer() arguments[index] = storage ++index