Skip to content

Commit e15126d

Browse files
authored
update: NativePlacement description (#5134)
1 parent 0a2664c commit e15126d

File tree

1 file changed

+4
-11
lines changed

1 file changed

+4
-11
lines changed

docs/topics/native/native-c-interop.md

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -126,28 +126,21 @@ val originalPtr = longValue.toCPointer<T>()
126126
The native memory can be allocated using the `NativePlacement` interface, for example:
127127

128128
```kotlin
129+
@file:OptIn(ExperimentalForeignApi::class)
129130
import kotlinx.cinterop.*
130131

131-
@OptIn(ExperimentalForeignApi::class)
132+
val placement: NativePlacement = // See below for placement examples
132133
val byteVar = placement.alloc<ByteVar>()
133-
```
134-
135-
Or:
136-
137-
```kotlin
138-
import kotlinx.cinterop.*
139-
140-
@OptIn(ExperimentalForeignApi::class)
141134
val bytePtr = placement.allocArray<ByteVar>(5)
142135
```
143136

144137
The most logical placement is in the object `nativeHeap`. It corresponds to allocating native memory with `malloc` and
145138
provides an additional `.free()` operation to free allocated memory:
146139

147140
```kotlin
141+
@file:OptIn(ExperimentalForeignApi::class)
148142
import kotlinx.cinterop.*
149143

150-
@OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
151144
fun main() {
152145
val size: Long = 0
153146
val buffer = nativeHeap.allocArray<ByteVar>(size)
@@ -165,10 +158,10 @@ automatically freed after leaving the scope.
165158
For example, a C function returning values through pointer parameters can be used like:
166159

167160
```kotlin
161+
@file:OptIn(ExperimentalForeignApi::class)
168162
import kotlinx.cinterop.*
169163
import platform.posix.*
170164

171-
@OptIn(ExperimentalForeignApi::class)
172165
val fileSize = memScoped {
173166
val statBuf = alloc<stat>()
174167
val error = stat("/", statBuf.ptr)

0 commit comments

Comments
 (0)