Does anyone have an example of getting a pointer t...
# kotlin-native
b
Does anyone have an example of getting a pointer to a local
Int
(or other primitive) without using
alloc
in
memScoped
? I'm trying to do it useing
usePinned
, but i'm having trouble navigating the types. Is the the right direction?
d
You can use
nativeHeap.alloc
. You can use
.ptr
to get a pointer to the allocated memory.
.value
to read it if it is a primitive. Any structure field turns into a property if you allocated a struct type.
Remember to free the memory.
I believe
usePinned
can only yield
CPointer
if you use it on an array.
pin.addressOf(0)
would give you what you want.
KNativePtr
cannot be used as a
CPointer
because it refers to a kotlin object, which is managed by the virtual machine, so it would be unsafe if you could use it as a
CPointer
.
memScoped
is something that C does not have, which just makes memory management more safe and simple in Kotlin. But I am sometimes worried about its performance. Haven't tested it though. Nonetheless, if theres a function i expect to use a lot, I prefer allocating memory for it for the remainder of the process's life.
b
I see. I’m using sscanf, and I want to pass it pointers to local variables. I can do it fine using alloc. Just wanted to see if there was a more straightforward way of passing references to local variables, like you could in C
o
Not yet, however it is being considered for implementation further on
b
Great! Is there an issue I can follow?
o
Unlikely, but you could create one
u
Just as a side note, in C alloca is like memScoped.
d
What are the implications of using
alloca
in kotlin? Would it work without any.... quirks?
s
It is unlikely to work properly.
b
@Dico fwiw, I tested memscoped and manual alloc/free in a tight loop, and there was no noticeable difference
👍 2
d
memScoped
is indeed only a wrapper around
nativeHeap
.
👌 1
👍 1