Skip to content

Commit

Permalink
Implement methods for conversions between Long and CPointer
Browse files Browse the repository at this point in the history
  • Loading branch information
SvyatoslavScherbina committed Apr 17, 2017
1 parent 11ecf0c commit 20d95ae
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
10 changes: 10 additions & 0 deletions INTEROP.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ val intPtr: CPointer<IntVar> = 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<T>?` and `Long` available,
provided by `.toLong()` and `.toCPointer<T>()` extension methods:
```
val longValue = ptr.toLong()
val originalPtr = longValue.toCPointer<T>()
```

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.
Expand Down
4 changes: 4 additions & 0 deletions Interop/Runtime/src/main/kotlin/kotlinx/cinterop/Types.kt
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ val CPointer<*>?.rawValue: NativePtr

fun <T : CPointed> CPointer<*>.reinterpret(): CPointer<T> = interpretCPointer(this.rawValue)!!

fun <T : CPointed> CPointer<T>?.toLong() = this.rawValue.toLong()

fun <T : CPointed> Long.toCPointer(): CPointer<T>? = interpretCPointer(nativeNullPtr + this)

/**
* The [CPointed] without any specified interpretation.
*/
Expand Down
4 changes: 2 additions & 2 deletions Interop/Runtime/src/native/kotlin/kotlinx/cinterop/Varargs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ fun callWithVarargs(codePtr: NativePtr, returnValuePtr: NativePtr, returnTypeKin
// All supported arguments take at most 8 bytes each:
val argumentsStorage = argumentsPlacement.allocArray<LongVar>(totalArgumentsNumber)
val arguments = argumentsPlacement.allocArray<CPointerVar<*>>(totalArgumentsNumber)
val types = argumentsPlacement.allocArray<CPointerVar<*>>(totalArgumentsNumber)
val types = argumentsPlacement.allocArray<COpaquePointerVar>(totalArgumentsNumber)

var index = 0

Expand All @@ -87,7 +87,7 @@ fun callWithVarargs(codePtr: NativePtr, returnValuePtr: NativePtr, returnTypeKin
val typeKind = convertArgument(argument, isVariadic = isVariadic,
location = storage, additionalPlacement = argumentsPlacement)

types[index] = interpretCPointer<COpaque>(nativeNullPtr + typeKind.toLong())
types[index] = typeKind.toLong().toCPointer()
arguments[index] = storage

++index
Expand Down

0 comments on commit 20d95ae

Please sign in to comment.