user3484547
user3484547

Reputation: 11

Are `malloc` and `free` Java NDK Wrap the only way to overcome automatic recycling with Android?

Are malloc and free Java NDK Wrap the only way to overcome automatic recycling with Android?

inline jlong Java_edu_gnu_Native_malloc(jint size) {
    return (jlong)malloc(size);
}

inline void Java_edu_gnu_Native_free(jlong pointer) {
    free((void*)pointer);
}

Upvotes: 0

Views: 751

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27538

No, assuming you actually mean garbage collection. Your code example is a wild hack and would lead to endless problems, bugs and crashes if actually used in an app.

Chances are what you are really looking for are so-called global references. See the Local and Global References section in Google's JNI Tips for Android. Also see JNI Local Reference Changes in ICS for useful background information.

A better alternative may be to review your design and eliminate the need for overcoming garbage collection. Then your native code can simply use local references, which are much less error-prone.

Upvotes: 0

Stephen C
Stephen C

Reputation: 719229

(I assume "recycled" is intended to mean garbage collected ...)

No it isn't. If you make sure that a Java object remains reachable that it won't be recycled either. In fact, that's the normal way to deal with this. If you want to use an object, keep a reference to it. If your code can't find the reference any more it is a candidate for recycling.

If you wrap native malloc and free like your example does:

  • you risk creating a memory leaks and dangling references, potentially leading to hard crashes,

  • you have to jump through hoops (i.e. other native calls) to use the "pointers" for anything other than pointer comparison.

Upvotes: 1

Related Questions