Returning int array from C to Java as method parameter

Hello,
I've been trying to accomplish this
Java
int[] myArray = ... (filled with some data);
int retCode = myNativeCall(myArray);
if(retCode == 0)
doSomethingWith(myArray); //myArray gets overwritten with new data (with new size also) during the native call...
C
JNIEXPORT jint JNICALL Java_GenChav_rsaEncrypt(JNIEnv *env, jobject obj, jintArray myArray){
jintArray outbuf;
int[] new_array = .. // some function will fill this....
int new_array_length = ...//some function will give me the new size, not big, 512 max...
jint tmp[new_array_length]; //allocate..need something more ??
memcpy(tmp, new_array, new_array_lenght);
outbuf=(*env)->NewIntArray(env, new_array_length);
(*env)->SetIntArrayRegion(env, outbuf, 0, new_array_length, tmp);
myArray=outbuf;
I tought this way I would have a updated myArray ints on the Java program...
Any thought??

user5945780 wrote:
Ok, let's try to be constructive here...
How I do implement a return type for my method like a int array ?First realized it has nothing to do with JNI. So the same question and answer applies to java only.
>
like:
int[] return = myNativeCall();
Yes.
Then I will look for return[0], if it is == to 0, fine, it means a successful calculation by the native code. Not sure what that means. The structure of what you return it up to you.
It can help when you are unsure of what to do in JNI....write a pseudo representation of what you want to do in a java method. Then translate that java method into JNI, everything in the pseudo method must be in the JNI code.

Similar Messages

  • Need help on returning arrays from C++ to Java

    Hi all, I hava a C++ application that contains a method that will return a float array to Java. I was able to write the Java Code, the JNI code to call the C++ method and compile them successfully. However on calling the native method from Java, the data in the array returned was not what I want. Please look through my code and see what is wrong with it.
    My Java Code:
    public native float[] Statistics(int inputKey); // This is the native method
    public float[] Stats(int k){ //Java method to call the native method so that I can use it in a Bean for a JSP.
    inputKey = k;
    float[] p = new float[4];
    p = Statistics(inputKey);
    return p;
    For this native method, an integer is passed from Java to the native side and the native method will use this integer to generate a float array size of 4 and populate it with data and return it back to Java.
    My JNI code
    extern "C"
    JNIEXPORT jfloatArray JNICALL
    Java_com_jspsmart_upload_FinalWaterMark_Statistics(JNIEnv *env, jobject obj, jint inputKey)
         jfloatArray floatArray = env->NewFloatArray(4); //This creates a new Java floatArray to store the C++ array
         CWatermarker2App p; // This is the C++ class to be used
         jfloat *stats = p.OnWatermarkStatistics(inputKey) // The C++ method returns a float pointer for an array of size 4
         env->SetFloatArrayRegion(floatArray, 0 , 4 , stats); //storing the C++ float array into the Java float Array
         return floatArray; // return the Array to Java
    In this example, I should have the data returned as [4952.0 2529.0 1706.0 33.6] in the array.
    But i am getting junk instead like 2.53E-23, 1.402E-15 etc..
    Is this a type conversion mistake?
    Please help!

    The first thing I notice - probably not the problem - is the line defining p. There is no reason to define this as an array of size 4, because the return from the native method is going to wipe that definition, replacing it with the return value of the native method. Alternatives:
    1. float[] p = null.
    2. float[] p = Statistics(inputKey);
    3. return Statistics(k);

  • Return an array from dll to labview

    Hello,
    I am using "Call Library Function" where I call a C function from Labview.
    Now .. I want to return an 1 dimensional array from C DLL back to Labview.
    Can someone provide an example code how to do it.
    When I configure parameter, there are options "Array Data Pointer", "Array Handle" and "Array Handle Pointer".
    When I take the first (the simple one), so there is no way labview can know how many items are in the array.
    But what is the right to take?
    Thanks in advance
    Kind Regards

    You would run into the same problem calling a function that returns an array in C, because you cannot determine the number of items in an array in C solely from the pointer value that a function returns.  Also, it's a bad idea to return an array of unknown size as a function's return value, because that makes the calling function responsible for deallocating the memory even though the called function allocated it.  If you don't know in advance how large the array will be, then a better approach is to allocate an array of sufficient size in the calling function (or in LabVIEW, in this case) and pass that by reference to the function, then have the function's return value indicate the number of values in the array that are actually filled with data.

  • How to return a char [][] from c++ to java with JNI

    hi , i am new to JNI and i am having some troubles with a special task :
    in fact i am supposed to treat some data stored in a char[100][100] value and then return the result to java , the result is the sam value bur modified i mean a char [100][100] variable too...
    i saw that we can rely on
    JNIEXPORT jobjectArray JNICALL Java_JNITest_newArray (JNIEnv *env, jclass, jint size )
    jobjectArray joa = ... );  // what in my case ?;
    jsize len1 = (jsize)env->GetArrayLength(joa);
    for (int i=0; i<l en1; i++)
    jintArray colonne = (jintArray)env->GetObjectArrayElement(joa, i);
    jsize len2 = (jsize)env->GetArrayLength(colonne);
    jint *element = env->GetIntArrayElements(colonne, 0);
    for(int j=0; j<len2; j++)
           jint res = element[j];
                 // process some treatment here
            // how now to return the result to java : joa modified !!
    [/code]
    may be some errors present in this piece of code ...but i rely on your help to have the solution!! please i am really desperated !                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    You know that any JNI function for an array handles or creats only one-dimensional array. But if you know Java array structure then with these functions you can create Java arrays of any dimensions.
    A Java multi-dimensional array is a set of nested one-dimensional arrays (consider dimensions from left to right). I give you only schema of this process. Let create the array of your type (for example, char [2][3]):
    1) create one-dimensional object array "[C"[/b] of size two for the first dimension (and assign it to some variable of type jobjectArray) ;
    2) create two three-dimentional char arrays and assign these local references to each element of the array created in prev. step;
    3) fill each array created in (2) with your data (characters);
    4) return to Java code the reference created in the step (1) and do not delete local references created in steps (1) and (2).

  • Return 2D array from web service

    Hi All,
    I am new to web services development and start developing web service using net bean 6.9. I want to create the web service which needs to return the 2-d array. So i created it like this
    public Object[][] getData(@WebParam(name = "startDate")
    String startDate, @WebParam(name = "endDate")
    String endDate) {
    HashMap hm= new HashMap();
    hm.put("key1", "val1");
    hm.put("key2", "val2");
    Object[][] twoDarray = new String[hm.size()][2];
    Object[] keys = hm.keySet().toArray();
    Object[] values = hm.values().toArray();
    for (int row = 0; row < twoDarray.length; row++) {
    twoDarray[row][0] = keys[row];
    twoDarray[row][1] = values[row];
    return twoDarray;
    But when i test the web service using SOAPui then it did not returning anything. Can anyone guide me where is the problem??
    Thanks
    Shuja

    Gi,
    not sure what you are doing there, but you can build the J2EE WebService from your working POJO, and create a Web Service proxy class from the WSDL description (of the deployed or local WSDL file). Then, using the proxy class, you can access the output of the WebService.
    Frank

  • Returning 2D array from a stored procedure

    hi,
    i'm trying to return a nested table from a procedure.can any one help me out i'm getting the fallowing error.
    SQL> ed
    Wrote file afiedt.buf
    1 declare
    2 TYPE data_t IS TABLE OF NUMBER
    3 INDEX BY PLS_INTEGER;
    4 TYPE array_t IS TABLE OF data_t
    5 INDEX BY PLS_INTEGER;
    6 array array_t;
    7 begin
    8 Sp_test(123,'12-jan-08',array);
    9 dbms_output.put_line(array (10) (1));
    10* end;
    11 /
    Sp_test(123,'12-jan-08',array);
    ERROR at line 8:
    ORA-06550: line 8, column 1:
    PLS-00306: wrong number or types of arguments in call to
    'SP_TEST
    ORA-06550: line 8, column 1:
    PL/SQL: Statement ignored
    The procedure is
    CREATE OR REPLACE PROCEDURE Sp_test(S_KEY NUMBER,V_DATE DATE, array_out OUT array_t) as....

    Below is the error i got when using the above suggestion.
    SQL> ED
    Wrote file afiedt.buf
    1 DECLARE
    2 TYPE data_t IS TABLE OF NUMBER
    3 INDEX BY PLS_INTEGER;
    4 TYPE array_t IS TABLE OF data_t
    5 INDEX BY PLS_INTEGER;
    6 begin
    7 Sp_test(123,'12-jan-08',array REPORT.ARRAY_T);
    8 dbms_output.put_line(array (10) (1));
    9* end;
    10 /
    Sp_test(123,'12-jan-08',array REPORT.ARRAY_T);
    ERROR at line 7:
    ORA-06550: line 7, column 32:
    PLS-00103: Encountered the symbol "REPORT" when expecting one of the
    following:
    . ( ) , * @ % & | = - + < / > at in is mod not range rem =>
    .. <an exponent (**)> <> or != or ~= >= <= <> and or like
    between ||
    The symbol "." was substituted for "REPORT" to continue.

  • C++ do not support  JNi && how to return the array from jni?

    hi,
    1.. I have created the Cpp file to implemement the native method but it seems that the native method can not complie rightly , it tells me follows
    error C2819: type 'JNIEnv_' does not have an overloaded member 'operator ->'
    c:\program files\microsoft visual studio\vc98\include\jni.h(764) : see declaration of 'JNIEnv_'
    c:\users\wangyue\desktop\java_gui\beattrack 5.6 - ������_������_������������ 5.7\beattrack.cpp(202) : error C2227: left of '->GetByteArrayRegion' must point to class/struct/union
    then I use the c file to paste the same code, it can complie rightly , why? I really need my native method to complie rightly in Cpp file, how to solve it?
    2.I want to return a double, for the most simple way, I do the following
    #include "RealBeatTrack_BeatTrack.h"
    JNIEXPORT jdoubleArray JNICALL Java_playaudio_BeatTrack_BeatTrack
    (JNIEnv *env, jobject j, jbyteArray data)
    jdouble outdata[4]={1,2,3,4};
    return (*env)->NewDoubleArray(env, outdata);
    then in the java code, I difine a array to receive it,
    say double mydata[] = new double[4];
    mydata= BeatTrack(buffedata);
    but the java comlier tells me the Exception in thread "Thread-2" java.lang.OutOfMemoryError: Java heap space?
    anyone can help me?
    Thanks

    thanks for your reply
    another problem of my!
    the jni pass the string, I then convert it to the
    const char* filename = env->GetStringUTFChars(fname,NULL);
    then I use the filename to opent the file but fails, what is the problem???
    FILE *fp= fopen(filename,"w"); // there are some problem here!!!
         fprintf(fp, "%s\n","wangyue fighting!");
    the error is as follows
    # An unexpected error has been detected by Java Runtime Environment:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0bfc1a55, pid=7040, tid=11384
    # Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode windows-x86)
    # Problematic frame:
    # C [beattrack.dll+0x1a55]
    # An error report file with more information is saved as:
    # D:\programs\playAudio\hs_err_pid7040.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    # The crash happened outside the Java Virtual Machine in native code.
    # See problematic frame for where to report the bug.
    #

  • How to return a array which be created in native method?

    i wrote my native method like this:
    jintarray array=env->Newintarray(10);
    jint* p=env->GetIntArrayElements(array,0);
    for(int i=0;i<10;i++){
    p=i;
    return array;
    the result is that i got a array which has ten elements and all the elements are 0.
    it seems the value of the array never be chenged.
    how can i do? where is the mistake? how can i get the correct result?

    Not quite clear what you are trying to do.
    o You create a java in array, which will be initialized to zeroes.
    o You then asked to access that array (as p), but you didn't pass a pointer to a boolean so it can tell you whether p points into the java array, or is a separate memory area.
    o You assigned a bunch of int values to p - not p[0], p [1], ....?
    o You returned to java the original array.
    Here's some (untested) code that will likely work:
    jBoolean isCopy;
    jintarray array=env->Newintarray(10);
    jint* p=env->GetIntArrayElements(array,&isCopy);
    for(int i=0;i<10;i++){
    p=i;
    if (isCopy == JNI_TRUE)
    env->ReleaseIntArrayElements(array, p, 0);
    return array;

  • Calling a web service from BPEL using java web methods

    Hello everyone,
    I have an application my BPEL process should connect to. The application which is a web service needs to be called using pre defined web methods defined in java from my bpel process using Jdev 10g. Any suggestions in how I can go about doing that? Please I really need help

    Hi there,
    If you have defined already your partner links to the service you can use the BPEL API to invoke them from RMI. See this blog entry
    http://technology.amis.nl/2006/06/08/oracle-bpel-pm-invoking-a-remote-bpel-service-from-java-using-rmi/
    It'd be also good if you post the question on the bpel forum BPEL
    Thanks,
    JC

  • External java function that should return String array

    Hi everyone,
    I have a split function in plsql that takes 10 times longer a java tokenizer function that i was written. So, i want to use java external function to split my plsql strings into pieces.
    I can write a java external procedure that returns types like int, float and String types. I have no problem about it.
    My problem is returning an array of strings. I found a book that has an example about how can we get directory list in plsql with java external procedure.
    (code)
    import java.io.File;
    import java.sql.*;
    import oracle.sql.*;
    import oracle.jdbc.*;
    public class JFile {
    public static oracle.sql.ARRAY dirlist (String dir)
    throws java.sql.SQLException
    Connection conn = new OracleDriver().defaultConnection( );
    ArrayDescriptor arraydesc =
    ArrayDescriptor.createDescriptor ("DIRLIST_T", conn);
    File myDir = new File (dir);
    String[] filesList = myDir.list( );
    ARRAY dirArray = new ARRAY(arraydesc, conn, filesList);
    return dirArray;
    CREATE OR REPLACE FUNCTION dirlist (dir IN VARCHAR2)
    RETURN dirlist_t
    AS
    LANGUAGE JAVA
    NAME 'myFile.dirlist(java.lang.String) return oracle.sql.ARRARY';
    (code)
    I could compile this source file in localhost but not remotehost. There are jar files ( import oracle.sql.*; import oracle.jdbc.*; ) that should be added to remote classpath. ( others have already added java classpath ). But, which classpath i should add? Oracle has own JVM and Classpath, probably i should upload these jar files to oracle classpath. Am i wrong? How can i do? Can you explain in detail? How can i return string array from java external function in Oracle ?
    I am using Oracle 11.1.0.7 on Solaris Sparc Machine.

    Hi,
    What do you mean "compile in remote host"
    Aren't you using the loadjava tool? - that should be enough, the RDBMS already "has" the jars needed.
    [A must read|http://download.oracle.com/docs/cd/B28359_01/java.111/b31225/chone.htm#BABCFIIF]
    Regards
    Peter

  • Returning arrays from function

    Hi all,
    Can u please guide me in how to return an array from function .
    Is it possible or not ??
    If it is possible please tell me how to declare the function(prototype) that returns string array
    and how to return the string array..
    Thanks in Advance

    Hi all,
    Can u please guide me in how to return an array from
    function .
    Is it possible or not ??
    If it is possible please tell me how to declare the
    function(prototype) that returns string array
    and how to return the string array..
    Thanks in Advance
    public String [] methodReturnsAnArray()
    }

  • Returning multiple values from a method

    I have to return a string and int array from a method (both are only of size 5 for a total of 10) What would be considered the best manner in which to do this ?
    Dr there's 10 points in it for you or whoever gives me the best idea ;-P

    hey here it is easy that you can return many things
    what ever you want from a single method man....
    you know the main thing what you have to do is.....
    Just create a VECTOR or LIST object, then add all the
    values what ever you want to return like string and
    int array like etc...
    Then make the method return type is VECTOR and after
    getting the Vector you can Iterate that and you can
    get all the values from that method what ever you
    want....
    jus try this,,,,,,,,,,
    Its really work......
    reply me..but it relies purely on trust that the returned collection would contain exactly the right number and type of arguments

  • How to conver vector to Int array

    Hi
    I know toArray method can be used to convert vector to an array but what if I want to convert it to an int array?
    Vector v = new Vector();
    int r [] = new int [1];
    v.add(2);
    r = v.toArray()//gives errorHow can I cast it to return int Array rather than object array?

    Vector v = new Vector(10);
    for(int i = 0; i < 10; i++) {
        v.add(i);
    int r[] = new int[v.size()];
    for(int i = 0; i < r.length; i++) {
        String value = v.elementAt(i).toString();
        r[i] = Integer.valueOf( value ).intValue();
        System.out.println(r);

  • Return array of varchar from oracle to java

    Hi,
    I am trying to return an array of varchar from database to java. However, when I print the values in java, it prints hexadecimal values like this.
    0x656E7472792031
    0x656E7472792032
    0x656E7472792033
    0x656E7472792034
    I am using oracle 9.2.0.5.0 and jdk 1.4
    This happens only when the NLS character set of the database is WE8MSWIN1252 (default character set).
    It works fine on databases with UTF8 and US7ASCII character sets.
    Any leads to the reason behind this behaviour is greatly aprpeciated.
    Here's the code snippet...
    <code>
    //USER DEFINED TYPE
    create or replace type SimpleArray
     as table of varchar2(30)
    </code>
    <code>
    // FUNCTION RETURNING USER DEFINED TYPE
    create or replace function getSimpleArray return SimpleArray
     as
     l_data simpleArray := simpleArray();
     begin
      for i in 1 .. 10 loop
          l_data.extend;
          l_data(l_data.count) := 'entry ' || i;
        end loop;
        return l_data;
      end;
    </code>
    <code>
    // JAVA METHOD
    public static void main(String[] args)
         try {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String url = "jdbc:oracle:thin:@localhost:1521:db1252";
              Connection conn = DriverManager.getConnection(url, "ring", "ring");
              CallableStatement stmt = conn.prepareCall("{? = call "
                             + "getSimpleArray" + "}");
              Array rs = null;
              ResultSet rsltSet = null;
              stmt.registerOutParameter(1, Types.ARRAY, "SIMPLEARRAY");
              stmt.execute();
              rs = stmt.getArray(1);
              String[] values = (String[]) rs.getArray();
              System.out.println(rs.getBaseTypeName());
              System.out.println(values.length);
              for (int i = 0; i < values.length; i++) {
                   System.out.println(values);
              rsltSet = rs.getResultSet();
         } catch (Exception e) {
              System.err.println("Got an exception! ");
              System.err.println(e.getMessage());
    </code>
    Thanks,
    Vivek

    Actually, check nls_charset12.zip. It looks like 9.2.0.5 driver contains only the *.zip version. Make sure that the file exists in the directory pointed by the CLASSPATH. Use full path, do not use %ORACLE_HOME%.
    I have reproduced your problem without nls_charset12.zip and I could not reproduce it with the file in the class path. Double-check how classpath is set in your environment. Maybe it is overriden by some configuration or batch file.
    -- Sergiusz

  • Returning an array type from a local method in Web Dynpro Java application

    Hi,
    In my project, we have a requirement to display 18 rolling months along with the year, starting from current month.
    How I am going to approach is that I will get the system date and get the current month and send the month and year value to a local method which will return 18 rolling months along with the year.
    But, when I tried to create a new method there is no option to return an array type. It was greyed out.
    So, we can not return an array type from a method from Web Dynpro for Java application?
    If so, what is the alternative and how am I going to achieve it?
    I will appreciate your help!
    Regards
    Ram

    HI
    You can create new methods in
      //@@begin others
      private ArrayList MyMethod(){
           // ** Put your code here
           return new ArrayList();
      //@@end
    Other option are create a context node with cardinality 0...n with one or more attributes, and in your method create the needed registers into this node. To read this values, you only need to read your context node.
    Best regards
    Edited by: Xavier Aranda on Dec 2, 2010 9:41 AM

Maybe you are looking for

  • How to get security roles

    Hi All, I want to know how to get the security roles which we configured in adfsecurity. Regards, Smaran

  • JDeveloper 10.1.3.2.0 and JWE

    Hi, I want to create a wireless application. I've JDev version 10.1.3.2.0. When I am placing jwe.jar file in /jdev/lib/ext directory and starting my JDev, I am getting bunch of error messages: Severe(2,381): No class def found for addin oracle.panama

  • Help to reset monitor resolution?

    Greetings, I have a G5 Quad with an Ati x1900 graphics card running into a 52" Samsung LCD. This was working fine through a dvi-vga adaptor until I switched the monitor resolution from 1920X1080 to 1360X768 which is not supported by the monitor .....

  • Blank Dialog Boxes with PUSH ME blue buttons

    Greetings All, I'm a fairly experienced Mac User and have been a bit surprised recently to be getting blank dialog boxes with buttons. Could it be some sort of spyware hoping I'll just push the blue buttons? It seems to come up once my Mac has been o

  • Export PDF conversion process

    Where does the conversion take place for Export PDF?  PC or website?  If website are document copies cleanly removed on completion?