Hello, I just started using Kotlin/Native and I'm a bit confused with how I can turn a CValue<T> into T. I know useContents exist but is there a more practical way of doing this?
Copy code
val result: CValue<Thing> = my_c_function_call()
val resultButRealThisTime: Thing = ???
Doing
Copy code
val result = my_c_function_call()
val resultButReal: Thing? = null
result.useContents { resultButReal = this@useContents }
Works, but looks awful and I don't think that's how you're supposed to do that
r
russhwolf
02/22/2021, 1:40 PM
Not totally sure but I think you could do something like
Copy code
val resultButReal: Thing = result.useContents { this }
m
Matthieu Stombellini
02/22/2021, 2:00 PM
True, that's much simpler, thanks for the tip! I'm still wondering if that wouldn't cause memory-management issues, the description of useContents in the docs seem to say that it allocates memory inside useContents? I'm pretty confused
Matthieu Stombellini
02/22/2021, 2:44 PM
Doesn't look like that's working, the allocation is temporary and "escaping" stuff from useContents leads to ugly errors reported by valgrind
r
russhwolf
02/22/2021, 4:07 PM
Does that same issue not happen with your original code?
m
mkrussel
02/22/2021, 5:15 PM
Should happen with both. My guess is both implementations creates undefined behavior.
In general you need to do whatever you need the value for inside the
useContents
method. If you need to be storing it for later use, store it as a CValue.
d
Dominaezzz
02/22/2021, 9:15 PM
Is
Thing
a struct? If so, you'll have to allocate with
nativeHeap
to do what you want here.
Although it's best to leave it inside