https://kotlinlang.org logo
#kotlin-native
Title
# kotlin-native
a

Adam S

12/14/2023, 12:16 PM
I've got a data class
Copy code
data class MyVec2(val x: Float, val y: Float)
and an equivalent C struct
Copy code
typedef struct Vec2 {
    float x;
    float y;
} Vec2;
and a C function that takes a pointer to a vector
Copy code
some_function(Vec2 *value)
When I call this function from Kotlin do I need a memory scope to create and pass a Vec2 pointer, or is it possible without? I want to be able to instantiate vectors without a memory scope (because most of the time passing a pointer is not necessary, so it adds some overhead/complexity that I'd like to avoid)
j

Jan Holešovský

12/15/2023, 6:49 AM
I cannot imagine how it would work without memScoped 😉 - I believe yes, you need a memScoped. What is your concern about its usage?
a

Adam S

12/16/2023, 9:10 AM
there are a few things. • It's annoying to have to either require passing a memscope into the Vector constructor, or using an extension function (which then requires every function that wants to create a vector is also an extension function for memscope) • from rough experimentation memscoped performance is not good when there are lots of vectors • performance is better without copying to/from a memscope (but maybe using nativeheap everywhere will be fine?)
yes it makes sense that a memory scope is required, but I was hoping there was some other way of exposing the primitive values as a cValue struct pointer :)
For example: using
nativeHeap.alloc<Vec2> { x = 1f; y = 2f }
is ~5 times slower than
MyVec2(x = 1f, y = 2f)
j

Jan Holešovský

12/17/2023, 10:34 PM
Comes to my mind - would it be an option for you just to extend the C api to have also some_function(float x, float y), and call that directly? 😉 That might solve your problem (?)
a

Adam S

12/17/2023, 10:37 PM
good idea, but I need to pass a pointer in because the C function will update the vector values
j

Jan Holešovský

12/17/2023, 10:42 PM
Hmm, then what about if that some_function() with 2 params returns struct with the new values? To consume that, you don't need memScoped I think, maybe it'll perform better?
a

Adam S

12/17/2023, 10:55 PM
possibly! But then I would have to write C 🙃. I think it might be too complicated to do it for all the functions, but I'll experiment and see...
k

Krystian

12/18/2023, 10:27 AM
This is exactly why I gave up on Raylib binding. The amount of overhead and complexity just to get simple stuff done was tedious
a

Adam S

12/19/2023, 12:39 PM
I think what I'll try to do is create a
Vec2Var
Kotlin class, similar to how there's a
IntVar
, specifically for passing a pointer into C functions and reading the value
and I realised the ~5 times slower benchmark was run in debug mode - maybe the result is different in release mode!
j

Jan Holešovský

12/19/2023, 12:43 PM
That might be good news 🙂