Reputation: 11
I have a little bit of a fight with Kotlin Native and the runtime. In short: I am building a jvmti agent, linking a dynamic library.
Now I have following case, what I like to achieve can be expressed in C like:
char* class_sig;
(*jvmti)->GetClassSignature(object_klass, &class_sig, NULL)
do something with class_sig....
(*jvmti)->Deallocate((unsigned char*) class_sig);
So in that case the jvmti environment allocates the memory for class_sig, that is why I have to deallocate through the jvmti environment.
How can this be achieved in Kotlin? I am a little on the fence regarding calling nativeheap.alloc, wouldn't that cause a memory leak because the jvmti environment already allocates memory?
Or can I just do:
val signaturePtr = nativeHeap.alloc<CPointerVar<ByteVar>>()
jvmti?.pointed?.pointed?.GetClassSignature?.invoke(jvmti, klass, signaturePtr.ptr, null)
Call jvmti dealloc?
Upvotes: 1
Views: 432
Reputation: 3177
Kotlin Native way is to use memScoped
blocks for such task. Take a look at official guide for C interop
If you write
memScoped {
val signaturePtr = alloc<CPointerVar<ByteVar>>()
//...
}
Kotlin will take care of memory deallocation inside memScoped
block, no need to invoke jmti Deallocate
Upvotes: 0