Given the WinAPI `CreateThread` function, how do I...
# kotlin-native
e
Given the WinAPI
CreateThread
function, how do I correctly pass a
this
reference (as a pointer) as a parameter to
entryPoint
?
Copy code
CreateThread(
  lpThreadAttributes = null,
  dwStackSize = 0u,
  lpStartAddress = staticCFunction(::entryPoint),
  lpParameter = this,
  dwCreationFlags = 0u,
  lpThreadId = null,
)

...

private fun entryPoint(parameter: COpaquePointer?): UInt {
  TODO()
}
l
You'll need to tell the gc to mark the Kotlin object as stable (can't be moved or collected) for as long as it's needed. You can use StableRef.create or call 'pin' on the object. Make sure to dispose the StableRef or unpin depending on which you use when it's no longer needed.
gratitude thank you 1
e
@Landry Norris so basically something like
Copy code
StableRef.create(this).asCPointer()
l
Yes. When you're done, you can convert the CPointer back to StableRef and dispose it. This tells the GC you don't need the variable to stay in the same place anymore.
e
@Landry Norris this only thing I'm not sure about is I'm doing all this on
this
, like I'm creating a stable ref to myself basically
Hopefully it doesn't break somewhere else
In regard to
staticCFunction
, I suppose that's ok as it is now.
l
I believe it's fine to create a StableRef on 'this', since it's a form of manual memory management. The memory holding 'this' can't be gc'ed while the StableRef is active, and it's fine if the StableRef gets gc'ed. It's just a binding to some runtime functions. Just make sure to dispose the StableRef when it's not needed anymore.
✔️ 1
e
The object I'm writing exposes a
dispose
function, to be used by clients. I suppose I'll dispose the
StableRef
inside
dispose
One last question to complete the puzzle.
Copy code
parameter: COpaquePointer?
This parameter will end up representing the
this
instance. How do I dereference the pointer and change its representation to
this
class?
l
If I remember correctly, you can call '.asStableRef().get<Foo>()' on the pointer.
e
Yup, you're right!
Copy code
parameter?.asStableRef<MyClass>()?.get()
d
Considering the use case, you can just dispose the
StableRef
in your
staticCFunction
as the very first thing it does.
e
Thanks @Dominaezzz, it makes sense, as then everything is handled after the entry point.