title: Java jbytearray access in c (JNI)
body: <p>I have a set of java classes that I need at my job to be ran in C/C++.</p>
  
  <p>And, since I am fairly new to java, I am taking it one step at a time.  I've gotten to be able to call java with string, int double etc, but the end results will be getting a byte array back (a pdf document) so I tried sending back a simple two element byte array.</p>
  
  <p>Here is the java:  </p>
  
  <pre><code>public class ReturnData
  {
      int returnValue;
      String Log;
      Byte[] data = new Byte[2];
  
       public ReturnData(int nRetVal, String szLog)
       {
           this.data[0] = 100;
           this.data[1] = 12;
           this.returnValue = nRetVal;
           this.Log = szLog;
       }
  }
  </code></pre>
  
  <p>and here is the c++ code (JNI initialization removed.  It works for simple types so ...)</p>
  
  <pre><code>jbyteArray jbyteData = (jbyteArray)jniEnvironment-&gt;GetObjectField(jobjRetData,
      jniEnvironment-&gt;GetFieldID(clsReturn, "data", "Ljava/lang/ByteArray;"));
  </code></pre>
  
  <p>And now anytime I access the jbyteData element, such as:</p>
  
  <pre><code>jsize len = jniEnvironment-&gt;GetArrayLength(jbyteData);
  </code></pre>
  
  <p>I get an Exception</p>
  
  <pre><code>System.AccessViolationException was unhandled
  Message: Attempted to read or write protected memory. This is often an indication that other 
  memory is corrupt.
  </code></pre>