Adam S
06/09/2024, 8:12 AMextern "C"
wrappers for the C++ library. But I am very stuck on a problem, because I am confused by C++ scoping/pointers/references/etc. Help would be very appreciated!
I'm stuck trying to call a static function: Quat:sIdentity()
Here's the wrapper function I've written:
struct JoltC_Quat { void *obj; };
typedef struct JoltC_Quat JoltC_Quat_t;
JoltC_Quat_t * JoltC_Quat_sIdentity() {
const Quat& resultValue = Quat::sIdentity();
JoltC_Quat_t* result = new JoltC_Quat_t();
result->obj = const_cast<void*>(reinterpret_cast<const void*>(&resultValue));
return result;
}
Which is correctly recognised by KN, and I've generated cinterop for it. However, when I call it and print the values, I expect to see [0,0,0,1]
, but why does it print [2.3234582E-38, 1.4E-45, 8.3204753E-38, 3.4438E-41]
?
I had this working a few days ago! I'm pretty sure I haven't changed anything!Adam S
06/09/2024, 8:15 AMimport com.jrouwe.jolt.cinterop.internal.*
import kotlinx.cinterop.*
fun main() {
val qsi = JoltC_Quat_sIdentity()
?: error("null qsi")
println("qsi: $qsi")
println("qsi: ${qsi.pointed}")
println("qsi: ${qsi.coordsString()}")
}
private fun CPointer<JoltC_Quat>.coordsString(): String =
buildString {
append("[")
append(JoltC_Quat_GetX(this@coordsString))
append(", ")
append(JoltC_Quat_GetY(this@coordsString))
append(", ")
append(JoltC_Quat_GetZ(this@coordsString))
append(", ")
append(JoltC_Quat_GetW(this@coordsString))
append("]")
}
Which prints
qsi: CPointer(raw=0x600001e28140)
qsi: kotlinx.cinterop.NativePointed@e10218
qsi: [2.3234582E-38, 1.4E-45, 8.3204753E-38, 3.4438E-41]
Adam S
06/09/2024, 8:15 AMfloat JoltC_Quat_GetX(
JoltC_Quat_t * self
) {
Quat * selfCpp = static_cast<Quat *>(self->obj);
return selfCpp->GetX();
}
ephemient
06/09/2024, 9:36 AM&resultValue
that's definitely wrong, it's a dangling pointer after the function returnsAdam S
06/09/2024, 10:16 AMAdam S
06/09/2024, 10:29 AM&resultValue
pointed to the actual address, but when I run it again the address has been overwritten by something elseAdam S
06/09/2024, 4:26 PMJoltC_Quat_t * JoltC_Quat_sIdentity() {
Quat * resultPtr = new Quat();
*resultPtr = Quat::sIdentity();
JoltC_Quat_t * result = new JoltC_Quat_t();
result->obj = reinterpret_cast<void *>(resultPtr);
return result;
}
Klitos Kyriacou
06/10/2024, 8:16 AMresultPtr
. (And I'm not suggesting you should free it in this function, as you would then end up with a dangling pointer again.)Adam S
06/10/2024, 9:37 AMKlitos Kyriacou
06/10/2024, 9:40 AMGetX
etc you can make self.obj
return the object instead of a pointer to the object and then you won't have to free it.Adam S
06/10/2024, 9:40 AMmemScope.defer { CThing_Destroy(foo) }
Adam S
06/10/2024, 9:42 AMAdam S
06/10/2024, 9:46 AM