When a C function needs a struct as parameter, you have to allocate it on the heap, but in most cases, we could just store the struct in the output binary.
Proposing: static allocation functions.
Functions that are resolved at compile time.
fun allocStatic(size: Int, align: Int): NativePointed
,
fun <T: CVariable> allocStatic(): T
,
fun <T: CVariable> allocStaticArray(length: Int): CArrayPointer<T>
These functions are equal to defining the struct as a global.
Example Kotlin code:
fun a(): Float {
val v1 = allocStatic<V2fVar>()
val v2 = allocStatic<V2fVar>()
getDim(v1.ptr)
getPos(v2.ptr)
return v1.x / v2.x + v1.y / v2.y
}
Equivalent C code:
struct V2f v1;
struct V2f v2;
float a() {
getDim(&v1)
getPos(&v2)
return v1.x / v2.x + v1.y / v2.y;
}
I personally have code that needs to pass a lot of structs to C functions in unpredictable places, and having to heap allocate every one of them, slows down the program. (Yes, I am aware that it uses arena allocators)
The problem with these functions:
A user might get confused and think that these functions are executed at runtime and allocate per call instead of per usage.