⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jnistring.html

📁 jdbc书
💻 HTML
📖 第 1 页 / 共 2 页
字号:

<A NAME="pin"></A>
<H3>Pinning Array</H3>

When retrieving an array, you can specify if this is a copy
(<CODE>JNI_TRUE</CODE>) or a reference to the array residing in
your Java language program (<CODE>JNI_FALSE</CODE>).
If you use a reference to the array, you will want the array to stay
where it is in the Java heap and not get moved by the garbage
collector when it compacts heap memory. To prevent the array references 
from being moved, the Java virtual machine pins the array into 
memory. Pinning the array ensures that when the array is released,
the correct elements are updated in the Java VM. 

<P>
In the <CODE>loadfile</CODE> native method example from the
previous section, the array is not explicitly released. One way 
to ensure the array is garbage collected when it is no longer needed
is to call a Java language method, pass the byte array instead, and
then free the local array copy. 
This technique is shown in  the section on <A HREF="#multi">Multi-Dimensional
Arrays</A>. 

<A NAME="object"></A>
<H3>Object Arrays</H3>

You can store any Java language object in an array with the
<CODE>NewObjectArray</CODE> and <CODE>SetObjectArrayElement</CODE> 
function calls. The main difference between an object array and an
array of primitive types 
is that when constructing a <CODE>jobjectarray</CODE> type, 
the Java language class is used as a parameter. 

<P>
This next C++ example shows how to call <CODE>NewObjectArray</CODE>
to create an array of <CODE>String</CODE> objects. The size of the 
array is set to five, the class definition is returned from a call
to <CODE>FindClass</CODE>, and the elements of the array are initialized
with an empty string. The elements of the array are updated by calling 
<CODE>SetObjectArrayElement</CODE> 
with the position and value to put in the array.

<PRE>
  &#35;include &lt;jni.h&gt;
  &#35;include "ArrayHandler.h"

  JNIEXPORT jobjectArray JNICALL 
               Java_ArrayHandler_returnArray
  (JNIEnv *env, jobject jobj){

    jobjectArray ret;
    int i;

    char *message[5]= {"first", 
	"second", 
	"third", 
	"fourth", 
	"fifth"};

    ret= (jobjectArray)env-&gt;NewObjectArray(5,
         env-&gt;FindClass("java/lang/String"),
         env-&gt;NewStringUTF(""));

    for(i=0;i&lt;5;i++) {
        env-&gt;SetObjectArrayElement(
		ret,i,env-&gt;NewStringUTF(message[i]));
    }
    return(ret);
  }
</PRE>

The Java class that calls this native method is as follows:

<PRE>
  public class ArrayHandler {
    public native String[] returnArray();
    static{
        System.loadLibrary("nativelib");
    }

    public static void main(String args[]) {
        String ar[];
        ArrayHandler ah= new ArrayHandler();
        ar = ah.returnArray();
        for (int i=0; i&lt;5; i++) {
           System.out.println("array element"+i+ 
                                 "=" + ar[i]);
        }
    }
  }
</PRE>

<A NAME="multi"></A>
<H3>Multi-Dimensional Arrays</H3>

You might need to call existing numerical and mathematical
libraries such as the linear algebra library CLAPACK/LAPACK
or other matrix crunching programs from your Java language
program using native methods.
Many of these libraries and programs use two-dimensional
and higher order arrays. 

<P>
In the Java programming language, any array that has more than
one dimension is treated as an array of arrays.
For example, a two-dimensional integer array is handled as an array of 
integer arrays. The array is read horizontally, or what is
also termed as row order. 

<P>
Other languages such as FORTRAN use column ordering so extra care is needed 
if your program hands a Java language array to a FORTRAN function. Also, 
the array elements in an application written in the Java programming 
language are not guaranteed to be contigous in memory. Some numerical 
libraries use the knowledge that the array elements are stored next to 
each other in memory to perform speed optimizations, so you might need
to make an additional local copy of the array to pass to those functions.

<P>
The next example passes a two-dimensional array to a native method which
then extracts the elements, performs a calculation, and calls a Java
language method to return the results.

<P>
The array is passed as an object array that contains an array of
<CODE>jints</CODE>. The individual elements are extracted by first
retrieving a <CODE>jintArray</CODE> instance from the object array by
calling <CODE>GetObjectArrayElement</CODE>, and then extracting the elements
from the <CODE>jintArray</CODE> row. 

<P>
The example uses a fixed size
matrix. If you do not know the size of the array being used, the 
<CODE>GetArrayLength(array)</CODE> function returns the size of the outermost
array. You will need to call the <CODE>GetArrayLength(array)</CODE> function
on each dimension of the array to discover the total size of the array.

<P>
The new array sent back to the program written in the Java langauge
is built in reverse.
First, a <CODE>jintArray</CODE> instance is created and that instance
is set in the object array by calling <CODE>SetObjectArrayElement</CODE>.

<PRE>
public class ArrayManipulation {
  private int arrayResults[][];
  Boolean lock=new Boolean(true);
  int arraySize=-1;

  public native void manipulateArray(
		int[][] multiplier, Boolean lock);

  static{
    System.loadLibrary("nativelib");
  }
 
  public void sendArrayResults(int results[][]) {
    arraySize=results.length;
    arrayResults=new int[results.length][];
    System.arraycopy(results,0,arrayResults,
                       0,arraySize);
  }

  public void displayArray() {
    for (int i=0; i&lt;arraySize; i++) {
      for(int j=0; j &lt;arrayResults[i].length;j++) {
        System.out.println("array element "+i+","+j+ 
          "= "  + arrayResults[i][j]);
      }
    }
  }

  public static void main(String args[]) {
    int[][] ar = new int[3][3];
    int count=3;
    for(int i=0;i&lt;3;i++) {
      for(int j=0;j&lt;3;j++) {
        ar[i][j]=count;
      }
      count++;
    }
    ArrayManipulation am= new ArrayManipulation();
    am.manipulateArray(ar, am.lock);
    am.displayArray();
  }
}

&#35;include &lt;jni.h&gt;
&#35;include &lt;iostream.h&gt;
&#35;include "ArrayManipulation.h"

JNIEXPORT void 
     JNICALL Java_ArrayManipulation_manipulateArray
(JNIEnv *env, jobject jobj, jobjectArray elements, 
                            jobject lock){

  jobjectArray ret;
  int i,j;
  jint arraysize;
  int asize;
  jclass cls;
  jmethodID mid;
  jfieldID fid;
  long localArrayCopy[3][3];
  long localMatrix[3]={4,4,4};

  for(i=0; i&lt;3; i++) {
     jintArray oneDim= 
	(jintArray)env-&gt;GetObjectArrayElement(
	                     elements, i);
     jint *element=env-&gt;GetIntArrayElements(oneDim, 0);
     for(j=0; j&lt;3; j++) {
        localArrayCopy[i][j]= element[j];
     }
  }

// With the C++ copy of the array, 
// process the array with LAPACK, BLAS, etc.

  for (i=0;i&lt;3;i++) {
    for (j=0; j&lt;3 ; j++) {
      localArrayCopy[i][j]=
        localArrayCopy[i][j]*localMatrix[i];
     }
  }

// Create array to send back
  jintArray row= (jintArray)env-&gt;NewIntArray(3);
  ret=(jobjectArray)env-&gt;NewObjectArray(
	3, env-&gt;GetObjectClass(row), 0);

  for(i=0;i&lt;3;i++) {
    row= (jintArray)env-&gt;NewIntArray(3);
    env-&gt;SetIntArrayRegion((jintArray)row,(
	jsize)0,3,(jint *)localArrayCopy[i]);
    env-&gt;SetObjectArrayElement(ret,i,row);
  }

  cls=env-&gt;GetObjectClass(jobj);
  mid=env-&gt;GetMethodID(cls, "sendArrayResults", 
                            "([[I)V");
  if (mid == 0) {
    cout &lt;&lt;"Can't find method sendArrayResults";
    return;
  }

  env-&gt;ExceptionClear();
  env-&gt;MonitorEnter(lock);
  env-&gt;CallVoidMethod(jobj, mid, ret);
  env-&gt;MonitorExit(lock);
  if(env-&gt;ExceptionOccurred()) {
    cout &lt;&lt; "error occured copying array back" &lt;&lt; endl;
    env-&gt;ExceptionDescribe();
    env-&gt;ExceptionClear();
  }
  fid=env-&gt;GetFieldID(cls, "arraySize",  "I");
  if (fid == 0) {
    cout &lt;&lt;"Can't find field arraySize";
    return;
  }
  asize=env-&gt;GetIntField(jobj,fid);
  if(!env-&gt;ExceptionOccurred()) {
    cout&lt;&lt; "Java array size=" &lt;&lt; asize &lt;&lt; endl;
  } else {
    env-&gt;ExceptionClear();
  }
  return;
}
</PRE>

<P>
_______<BR>
<A NAME="TJVM"><SUP>1</SUP></A> As used on this web site, 
the terms &quot;Java virtual 
machine&quot; or &quot;JVM&quot; mean a virtual machine 
for the Java platform.

<P ALIGN="RIGHT">
<FONT SIZE="-1">[<A HREF="#top">TOP</A>]</FONT>

</FONT>
</TD>
</TR>
</TABLE>





<!-- ================ -->
<!-- End Main Content -->
<!-- ================ -->

</TD>
</TR>
</TABLE>

<!-- Copyright Insert -->

<BR CLEAR="ALL">

<FORM ACTION="/cgi-bin/search.cgi" METHOD="POST">
<TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="5">   
  <TR>
    <TD VALIGN="TOP">
	
    <P ALIGN=CENTER>
    <FONT SIZE="-1" COLOR="#999999" FACE="Verdana, Arial, Helvetica, sans-serif">
    [ This page was updated: <!-- new date --> 2-Nov-99 ]</font></P>
    </TD>
  </TR>
  
  <TR>
    <TD BGCOLOR="#CCCCCC">
    <IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
  </TR>
  
  <TR>
    <TD>
    <CENTER>
    <FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
    <A HREF="http://java.sun.com/products/">Products &amp; APIs</A> | 
    <A HREF="/developer/index.html">Developer Connection</A> | 
    <A HREF="/developer/infodocs/index.shtml">Docs &amp; Training</A> | 
    <A HREF="/developer/support/index.html">Online Support</A><BR>
    <A HREF="/developer/community/index.html">Community Discussion</A> |
    <A HREF="http://java.sun.com/industry/">Industry News</A> | 
    <A HREF="http://java.sun.com/solutions">Solutions Marketplace</A> | 
    <A HREF="http://java.sun.com/casestudies">Case Studies</A>
    </FONT>
    </CENTER>
    </TD>
  </TR>
  
  <TR>
    <TD BGCOLOR="#CCCCCC">
    <IMG SRC="/images/pixel.gif" HEIGHT="1" WIDTH="1" ALT=""></TD>
  </TR>

  <TR>
    <TD ALIGN="CENTER">
    <FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
    <A HREF="http://java.sun.com/docs/glossary.html">Glossary</A> - 
    <A HREF="http://java.sun.com/applets/">Applets</A> - 
    <A HREF="http://java.sun.com/docs/books/tutorial/">Tutorial</A> - 
    <A HREF="http://java.sun.com/jobs/">Employment</A> - 
    <A HREF="http://java.sun.com/nav/business/">Business &amp; Licensing</A> - 
    <A HREF="http://java.sun.com/javastore/">Java Store</A> -
    <A HREF="http://java.sun.com/casestudies/">Java in the Real World</A>
    </FONT>
    </TD>
  </TR>

  <TR>
    <TD>
    <CENTER>
    <FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
    <a href="/siteinfo/faq.html">FAQ</a> |
    <a href="/feedback/index.html">Feedback</a> | 
    <a href="http://www.dynamicdiagrams.net/mapa/cgi-bin/help.tcl?db=javasoft&dest=http://java.sun.com/">Map</a> | 
    <A HREF="http://java.sun.com/a-z/index.html">A-Z Index</A>
    </FONT>
    </CENTER>

    </TD>
  </TR>
  
  <TR>
    <TD>

    <TABLE WIDTH="100%" CELLPADDING="0" BORDER="0" CELLSPACING="0">
      <TR>
        <TD WIDTH="50%">
        <FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
        For more information on Java technology<BR>
        and other software from Sun Microsystems, call:<BR>
        </FONT>
        <FONT SIZE="-1" FACE="Verdana, Arial, Helvetica, sans-serif">
        (800) 786-7638<BR></FONT>
        <FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
        Outside the U.S. and Canada, dial your country's 
        <A HREF="http://www.att.com/business_traveler/attdirecttollfree/">AT&amp;T&nbsp;Direct&nbsp;Access&nbsp;Number</A> first.<BR>
        </FONT>
        </TD>

        <TD ALIGN="RIGHT" WIDTH="50%">
        <A HREF="http://www.sun.com"><IMG SRC="/images/lgsun.gif" width="64" height="30" border="0" ALT="Sun Microsystems, Inc."></A><BR>
        <FONT SIZE="-2" FACE="Verdana, Arial, Helvetica, sans-serif">
        Copyright &copy; 1995-99
        <A HREF="http://www.sun.com">Sun Microsystems, Inc.</A><BR>
        All Rights Reserved. 
        <a href="http://www.sun.com/share/text/SMICopyright.html">Legal Terms</a>. 
        <A HREF="http://www.sun.com/privacy/">Privacy&nbsp;Policy</A>.
        </FONT>
        </TD>
      </TR>
    </TABLE>
	
    </TD>
  </TR> 
</TABLE>
</FORM>

<!-- End Copyright Insert -->


</BODY>
</HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -