title: Sending int[]s between Java and C
body: <p>I have some image processing Java code in Android that acts upon two large int arrays. Most of the time, Java is fast enough but I need to use C via JNI and the NDK to speed up a few operations.</p>
  
  <p>The only way I know that I can pass the data from the int arrays to C is to use ByteBuffer.allocateDirect to create a new buffer, copy the data to that and then make the C code act upon the buffer. </p>
  
  <p>However, I cannot see any way I can manipulate the data in this buffer in Java as if the buffer was an int[] or a byte[]. For example, a call to ByteBuffer.array() will fail on the newly created buffer. Is there any way to make this work?</p>
  
  <p>I have limited memory and want to reduce how many arrays/buffers I need. For example, it would be nice if I could use IntBuffer.wrap(new int[...]) to create the buffer and then manipulate the array backing the buffer directly in Java but I cannot do this because the only thing that seems to work here for JNI is ByteBuffer.allocateDirect.</p>
  
  <p>Are there any other ways to send data back and forth between C and Java? Can I somehow allocate memory on the C side and have Java send data directly to there?</p>
  
  <p>Edit: A benchmark comparing buffer use to int[] use:</p>
  
  <pre><code>int size = 1000;
  IntBuffer allocateDirect = java.nio.ByteBuffer.allocateDirect(4 * size).asIntBuffer();
  for (int i = 0; i &lt; 100; ++i)
  {
    for (int x = 0; x &lt; size; ++x)
    {
      int v = allocateDirect.get(x);
      allocateDirect.put(x, v + 1);
    }
  }
  
  int[] intArray = new int[size];
  for (int i = 0; i &lt; 100; ++i)
  {
    for (int x = 0; x &lt; size; ++x)
    {
      int v = intArray[x];
      intArray[x] = v + 1;
    }
  }
  </code></pre>
  
  <p>On a Droid phone, the buffer version takes ~10 seconds to finish and the array version takes ~0.01 seconds.</p>