How do I turn a string into a `CPointer<ByteVar...
# kotlin-native
m
How do I turn a string into a
CPointer<ByteVar>
? I only see
.cstr
documented but that turns it into a
CValues<ByteVar>
m
I don't think you can ? My current mental model is that
CPointer
is for something that lives on the heap (has reference semantics) while
CValues
has value semantics (might be a const string or something else, not sure)
You can alloc a
CPointer
and memcpy to it though:
Copy code
val src = "Hello".cstr
      val dst = allocArray<ByteVar>(src.size)
      memcpy(dst, src, src.size.convert())
(don't take this as gospel, it might very well be wrong about size, terminating zero and all that kind of thingies)
d
memScoped { yourFunction("The string".cstr.ptr) }
. Haven't done native in a while but this is a shortcut iirc.
👀 1
m
@Dominaezzz that one won't work since I need to return it, but why would I use that over, say, a StableRef (which I found as alternative)
1
d
Stable ref? How does that help you?
m
It allows me to get a pointer from a variable rather than having to allocate the string again and copy it into there which would lead to a memory leak
d
The pointer you get from stable ref is opaque. It doesn't point to any data you're allowed to touch. It's meant to be used for callbacks, like a C handle for Kotlin objects. Also they need to be released so you'll leak either way.