Hi, @agb1! Unfortunately, the documentation on C Interop can be misleading sometimes, some parts of it are slightly outdated. For now, there are two main ways you can send a string to a C function:
- allocating the memory inside of a memScoped block, as @Wasabi375 suggested, or
- instantiating an instance of
Arena
class, using it to allocate memory like this:
val ar = Arena()
val ref = "Hello".cstr.getPointer(ar)
...
ar.clear() // wipes all the memory allocated on the arena before
The main difference here will be the lifetime of the allocated object. The first approach guarantees that the memory won’t be cleaned till the end of the block. So, if you want this pointer to be fine for all program’s lifetime, it can be a bad idea to wrap all main()
lines into a one big memScoped
block. On the other side, memScoped
is a lot easier to use as there is no need to clear it manually. For a quick sending something to the C side, it fits much better IMHO.