1

I've been trying to wrap CPointer types of native objects with the idea that the object controls the lifespan of the underlying native object.

In C++ terms, I would do something like:

class T {
private:
  U other;
};

Or even:

class T {
public:
  T(){ other = new U; }
  ~T(){ delete other; }
private:
  U other;
};

Which I'm not even sure if would be correct, but the idea is simple: Object "other" is held by the object of type T.

The problem is that I don't know if that is even possible in Kotlin native:

class T {
  private val arena = Arena()
  private val ptr: Cpointer<U> = arena.alloc()
  // Should I delegate the free method to T?
}

As far as I am concerned, the arena will not reclaim the memory automatically, right? I have to call .free() or .clear().


Is there any way to achieve such effect? Or the only way is to use memScoped and calling arena's clear or ptr free manually?

Alternatively, what are the best approaches to prevent memory waste/leaking in K/N?

Sigma Octantis
  • 903
  • 1
  • 8
  • 25
  • I think you are asking about the thing discussed in [this](https://github.com/JetBrains/kotlin-native/issues/2327) issue on the Kotlin/Native Github. If it won't be enough, please let me know. – Artyom Degtyarev Aug 12 '19 at 09:09
  • 1
    Thanks @ArtyomDegtyarev ! Then the only way is to have an explicit method like free() or dispose() in my wrapper? If you answer I'll accept it gladly. Sad there are no other means, maybe looking at this problem from a C++ perspective is confusing me more than it helps – Sigma Octantis Aug 12 '19 at 18:15

1 Answers1

1

Kotlin/Native has no ways to work in a C++ manner as you wish. For now, best practice is still to provide your own dispose() methods in your class. In my answer, I am referring to this GitHub issue and this conversation in Kotlin's public Slack. I also recommend these resources as preferrable Kotlin/Native-discussing places.

Artyom Degtyarev
  • 2,704
  • 8
  • 23