0

I'm currently using SWIG to wrap a unsigned char* as a byte[]. I'm returning this type from C++ to the Java side of my code.

Thing is, I don't really know if the responsibility to free the memory for this array falls on the native code and / or wrap, or on the Java GC.

Right now I'm using this (don't mind the awful hack to get the size...):

%typemap(jni)     unsigned char * Image::getPixels "jbyteArray"
%typemap(jtype)   unsigned char * Image::getPixels "byte[]"
%typemap(jstype)  unsigned char * Image::getPixels "byte[]"
%typemap(javaout) unsigned char * Image::getPixels{
    return $jnicall;
}

%typemap(out) unsigned char * Image::getPixels {
    //There must be a proper way than using an implicit local variable name
    //from the generated cxx file...
    size_t length = arg1->getBpp() * arg1->getWidth() * arg1->getHeight();
    $result = jenv->NewByteArray(length);
    jenv->SetByteArrayRegion($result, 0, length, (const signed char*)$1);
}

Here, the NewByteArray looks completely in the wild, and I don't know if and where I should call a ReleaseByteArrayElements. I found this answers but I'm not sure if that's exactly the same case here.

JBL
  • 12,588
  • 4
  • 53
  • 84
  • Looks ok to me. `$result` holds a local reference to the byte array, and you shouldn't have to explicitly delete local references unless you create so many of them (e.g. in a loop) that you risk filling the local reference table. – Michael Apr 24 '17 at 10:48
  • So when I do that: `jenv->NewByteArray(length)` and "return" `$result`, the JVM takes ownership of that memory and will GC it? – JBL Apr 24 '17 at 11:08
  • 2
    That's what would happen if you did this from a plain native function. So unless SWIG is inserting some additional code that creates a global reference behind the scenes, I'd say this code will work fine. I suppose you could do a test where you create a `NewObject` of some class of your own where you have overridden `finalize()` and log when the object gets finalized. – Michael Apr 24 '17 at 11:42
  • Alright, thanks for the insight! – JBL Apr 24 '17 at 12:02

1 Answers1

0

ReleaseByteArrayelements is used with GetByteArrayElements, so you don't need it here.
You don't need to free anything. The array will be freed by the Java garbage collector once there are no references to it.

BenK
  • 333
  • 1
  • 6
  • 14