Hello, I just started using Kotlin/Native and I'm ...
# kotlin-native
m
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
Not totally sure but I think you could do something like
Copy code
val resultButReal: Thing = result.useContents { this }
m
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
Doesn't look like that's working, the allocation is temporary and "escaping" stuff from useContents leads to ugly errors reported by valgrind
r
Does that same issue not happen with your original code?
m
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
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
useContents
if you can so garbage collection still works.