Statically allocating `CVariable`s

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.

Now that I think about it, it would be better if we could just directly have CVariables in vars and vals.
In that case, there should also be a way to get the pointer to it, so we can pass it to C functions.
That would also allow us to store CVariables in classes directly, which would be way better than heap allocating them and then free it at a later time. That would not be too bad if there were destructors, but unfortionally, that’s not a thing in Kotlin.

1 Like