Filling empty java array in C method
Hi everyone,
I'm passing to a C method an empty byte array from the Java Side. I want the C method to fill the Java byte array and return it at the end of the method to the java side.
in the Java side, I have my byte array :
byte[] myArray = null;
then I'm passing the array to the C method as
myMethod(myArray)
in the C method I'M trying to access the array as follow :
myMethod(jbyteArray myArray)
jbyte* tab = *env)->GetByteArrayElements(env, myArray, 0);
I'm getting an error at runtime. Can somebody help me with that issue please ? Thanks
Sebastien
You are not passing a byte array, you are passing null.
If you want to pass a byte array you first have to create it using the new operator:
byte[] myArray = new byte[theSizeOfTheArray];
myMethod(myArray);If you want the JNI code to create the array, that is fine also, but in that case the native method would probably have to return the array instead of void.
Similar Messages
-
[JNI Beginner] GC of Java arrays returned by the native code
Hello all,
I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
"Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
- in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
jByteArray=(*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?
- if it's no more referenced (the example Java code just systemouts it and forgets it), will it be eligible to GC?
- if it is referenced by a Java variable (in my case, I plan to keep a reference to several replies as the business logic requires to analyze several of them together), do regular Java language GC rules apply, and prevent eligibility of the array to GC as long as it's referenced?
That may sound obvious, but what mixes me up is that the same tutorial describes memory issues in subsequent chapters: spécifically, the section on "passing arrays states that:
[in the example] the array is returned to the calling Java language method, which in turn, garbage collects the reference to the array when it is no longer usedThis seems to answer "yes" to both my questions above :o) But it goes on:
The array can be explicitly freed with the following call:
{code} (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);{code}Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is +not+ returned as is to a Java method)?
The tutorial's next section has a much-expected +memory issues+ paragraph, from which I quote:
By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, +unless the references are assigned, in the Java code, to a Java variable+, right?
If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
I also checked the [JNI specification|http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp1242] , but this didn't clear the doubt completely:
*Global and Local References*
The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.
Objects are passed to native methods as local references. All Java objects returned by JNI functions are local references. The JNI allows the programmer to create global references from local references. JNI functions that expect Java objects accept both global and local references. A native method may return a local or global reference to the VM as its resultAgain I assume the intent is that Global references are meant for objects that have to survive across native calls, regardless of whether they are referenced by Java code. But what worries me is that combining both sentences end up in +All Java objects returned by JNI functions are local references (...) and are automatically freed after the native method returns.+.
Could you clarify how to make sure that my Java byte arrays, be they allocated in C code, behave consistently with a Java array allocated in Java code (I'm familiar already with GC of "regular" Java objects)?
Thanks in advance, and best regards,
J.jduprez wrote:
Hello all,
I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
"Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
- in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
jByteArray=(*env)->NewByteArray(env, size);
(*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?It will be collected when it is no longer referenced.
The fact that you created it in jni doesn't change that.
The array can be explicitly freed with the following call:
(*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is not returned as is to a Java method)?
Per what the tutorial says it is either poorly worded or just wrong.
An array which has been properly initialized it a just a java object. Thus it can be freed like any other object.
Per your original question that does not concern you because you return it.
In terms of why you need to explicitly free local references.
[http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16785]
The tutorial's next section has a much-expected memory issues paragraph, from which I quote:
By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, unless the references are assigned, in the Java code, to a Java variable, right?As stated it is not precise.
The created objects are tracked by the VM. When they are eligible to be collected they are.
If you create a local reference and do NOTHING that creates an active reference elsewhere then when the executing thread returns to the VM then the local references are eligible to be collected.
>
If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.That is not precise. The scope is the executing thread. You can pass a local reference to another method without problem.
I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
It enables access to it to be insured across multiple threads in terms of execution scope. Normally you should not use them. -
Passing Array to Another Method
Hello, I created a program with an array in one of the methods. I have been trying to figure out how to correctly pass the array to another method in the same class. I know my problem is in my method delcaration statements. Could someone please show me what I am doing wrong? Please let me know if you have any questions. Thanks for your help.
import javax.swing.*;
import java.util.*;
class Bank1 {
public static void main(String[] args) {
Bank1 bank = new Bank1();
bank.menu();
//Main Menu that initializes other methods
public void menu( ) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the bank. Please choose from the following options:");
System.out.println("O - Open new account");
System.out.println("T - Perform transaction on an account");
System.out.println("Q - Quit program");
String initial = scanner.next();
char uInitial = initial.toUpperCase().charAt(0);
while (uInitial != 'O' && uInitial != 'T' && uInitial != 'Q') {
System.out.println("That was an invalid input. Please try again.");
System.out.println();
initial = scanner.next();
uInitial = initial.toUpperCase().charAt(0);
if (uInitial == 'O') newAccount();
if (uInitial == 'T') transaction();
//Method that creates new bank account
public Person[] newAccount( ) {
Person[] userData = new Person[1];
for (int i = 0; i < userData.length; i++) {
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter your first and last name:");
String name = scanner1.next();
Scanner scanner2 = new Scanner(System.in);
System.out.println("Enter your address:");
String address = scanner2.next();
Scanner scanner3 = new Scanner(System.in);
System.out.println("Enter your telephone number:");
int telephone = scanner3.nextInt();
Scanner scanner4 = new Scanner(System.in);
System.out.println("Enter an initial balance:");
int balance = scanner4.nextInt();
int account = i + 578;
userData[i] = new Person( );
userData.setName ( name );
userData[i].setAddress ( address );
userData[i].setTelephone ( telephone );
userData[i].setBalance ( balance );
userData[i].setAccount ( account );
System.out.println();
System.out.println("Your bank account number is: " + userData[i].getAccount());
return userData;
menu();
//Method that gives transaction options
public void transaction(Person userData[] ) {
System.out.println(userData[0].getBalance());Thank you jverd, I was able to get that to work for me.
I have another basic question about arrarys now. In all of the arrary examples I have seen, the array is populated all at once using a for statement like in my program.
userData = new Person[50];
for (int i = 0; i < userData.length; i++) In my program though, I want it to only fill the first array parameter and then go up to the main menu. If the user chooses to add another account, the next spot in the array will be used. Can someone point me in the right direction for doing this? -
Java Array Out Of Bounds Problem
In order to conduct an experiment in java array sorting algorithm efficiency, i am attempting to create and populate an empty array of 1000 elements with random, unique integers for sorting. I've been able to generate and populate an array with random integers but the problem is - for whatever size array I create, it only allows the range of numbers to populate it to be the size of the array, for instance, an array of size 3000 allows only the integer range of 0-3000 to populate it with or I get an out of bounds exception during runtime. How can you specify an integer range of say 0-5000 for an array of size < 5000? Any help is appreciated.
Another approach is to fill the array with an
arithmetic sequence, maybe plus some random noise:
array[i] = i * k + rand(k);or some such, so they are unique,
and then permute the array (put the elements
s in random order)
for (i : array.length) {
transpose(array, array[rand(i..length)]); }
Along those lines, java.util.Collections.shuffle can be used to randomly shuffle a List (such as an ArrayList). Create an ArrayList with numbers in whatever range is needed. Then call java.util.Collections.shuffle(myArrayList). [It is static in Collections--you don't need to [and can't] create a Collections object.] -
Writing empty byte array to outputstream
Does anyone know if writing an empty byte array to an outputstream will throw an IOException? I think a little bug in my code is causing this because all seems to work when the byte array is not empty.
Thanks in advance for any help.The (overridden) method write(byte[]) of java.io.OutputStream throws a java.lang.NullPointerException rather than java.io.IOException when byte[] is simply null.
-
I have too many books and not enough understanding on this subject.
I am trying to fill an object type array with values and am totally confused. In my application, I successfully create a constructor in one file and test the object with some values in another file. I have two objects for employee and would like to place the object values into an object array. There is plenty of information on int[] arrays, but little on object arrays.
After I can do the array fill:
I would like to provide object values with JOptionPane.
Change the print display to show all array elements
But one thing at a time.
I was thinking that objects exist first, then are loaded or filled into an object array. I seem to misunderstand as I am not performing the array fill very well. Following a book example seems to confuse me only more.
Thank you
//emp.java
import java.util.*;
public class Emp {
private int id;
private String name;
private double salary;
public Emp(int ident, String nm, double sal) {
id = ident;
name = nm;
salary = sal;
// method raise salary by 5 percent
double raise() { return salary * 1.05;} // ends raise method
// setters and getters
public String getName() { return(name); }
public double getSalary() { return(salary); }
public int getID() { return(id); }
public void setName(String nm) { name = nm; }
public void setSalary(double sal) { salary = sal; }
public void setID(int ident) { id = ident; }
}The test file
//EmpTest.java
import javax.swing.JOptionPane;
public class EmpTest {
public static void main(String[] args_) {
// Create object based on EmployeeTest2 class
// to add employee data to the array called empArray
Emp emp1 = new Emp(1,"Smith",2000);
Emp emp2 = new Emp(2,"Jones",2500);
//test and confirm the objects emp1 and emp2
int i;
String n;
double s;
double newsal;
// get the salary after the 5 percent raise
i = emp1.getID();
n = emp1.getName();
s = emp1.getSalary();
newsal = emp1.raise();
System.out.println("object Employee 1 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: " + newsal);
i = emp2.getID();
n = emp2.getName();
s = emp2.getSalary();
newsal = emp2.raise();
System.out.println("object Employee 2 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: " + newsal);
// get the number of employees with JOptionPane
String employeeCountString = JOptionPane.showInputDialog(
"Employee Database " +
"\nEnter the number of employees: ");
// convert into an integer empcount
int employeeCount = Integer.parseInt(employeeCountString);
// initialize the empArray.
Employee2[] empArray = new Employee2[employeeCount];
fill(empArray);
printContents(empArray);
} //end main method
private static void fill(Object[] my_arr) {
int i;
for (i = 0; i < my_arr.length; i = i + 1) {
// get the name from the keyboard
String employeeName = JOptionPane.showInputDialog(
"Enter the employee name: ");
// do something here to set the array element to employeeName
// get the salary
String employeeSalaryString = JOptionPane.showInputDialog(
"Enter the employee monthly salary: ");
//convert into a double
double employeeSalary = Double.parseDouble(employeeSalaryString);
//do something here to set array for salary
my_arr[i] = new Employee2(1,"S1",5); // temporary values here
} //ends for loop
} // ends method
private static void printContents(Object[] the_arr) {
int i;
for (i = 0; i < the_arr.length; i = i + 1) {
System.out.print("Element: " + i);
//System.out.println(" has the value : " + the_arr);
System.out.println(" has the value : " + i);
} //ends for loop
} // ends printContents method
} // ends EmpTest classwhat's the matter ?
Try this :
import javax.swing.JOptionPane;
public class EmpTest {
public static void main(String[] args_) {
// Create object based on EmployeeTest2 class
// to add employee data to the array called empArray
Emp emp1 = new Emp(1, "Smith", 2000);
Emp emp2 = new Emp(2, "Jones", 2500);
// test and confirm the objects emp1 and emp2
int i;
String n;
double s;
double newsal;
// get the salary after the 5 percent raise
i = emp1.getID();
n = emp1.getName();
s = emp1.getSalary();
newsal = emp1.raise();
System.out.println("object Employee 1 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: "
+ newsal);
i = emp2.getID();
n = emp2.getName();
s = emp2.getSalary();
newsal = emp2.raise();
System.out.println("object Employee 2 ID: " + i + " Name: " + n + " Old Salary: " + s + " New salary: "
+ newsal);
// get the number of employees with JOptionPane
String employeeCountString = JOptionPane.showInputDialog("Employee Database "
+ "\nEnter the number of employees: ");
// convert into an integer empcount
int employeeCount = Integer.parseInt(employeeCountString);
// initialize the empArray.
Emp[] empArray = new Emp[employeeCount];
fill(empArray);
printContents(empArray);
} // end main method
private static void fill(Object[] my_arr) {
int i;
for (i = 0; i < my_arr.length; i = i + 1) {
// get the name from the keyboard
String employeeName = JOptionPane.showInputDialog("Enter the employee name: ");
// do something here to set the array element to employeeName
// get the salary
String employeeSalaryString = JOptionPane.showInputDialog("Enter the employee monthly salary: ");
// convert into a double
double employeeSalary = Double.parseDouble(employeeSalaryString);
// do something here to set array for salary
my_arr[i] = new Emp(1, employeeName, employeeSalary); // temporary values here
} // ends for loop
} // ends method
private static void printContents(Object[] the_arr) {
int i;
for (i = 0; i < the_arr.length; i++) {
System.out.print("Element # "+i+" Name= "+ ((Emp)the_arr).getName());
System.out.print("Salary # "+i+" Salary = "+ ((Emp)the_arr[i]).getSalary());
} // ends for loop
} // ends printContents method
} // ends EmpTest class -
Hey
i want to fill up an array with a deck of cards
i don't really know how to do it
here is some code that will clarify the situation
public class Game {
public void Game() {
public static void main(String[] args){
Kaart[] kaarten;
kaarten = new Kaart[53];
int teller=0;
public class Kaart {
private String color;
private String value;
public void kaart(String kleur, String waarde){
this.color=kleur;
this.value=waarde;
public void Kaart(){
public void setColor(String kleur){
this.color=kleur;
public String getColor(){
return color;
public void setValue(String waarde){
this.value=waarde;
public String getValue(){
return value;
public String toString(){
return value + color;
}Ok, there is some light at the end of the tunnel
the array is filled till the 13th card of hearts. but the rest is empty
any ideas
and
i know the method vulArray() can be way shorter
public class Game {
private Card[] deck;
public Game() {
deck = new Card[53];
public void vulArray() {
for (int i = 0; i < 53; i++) {
switch (i) {
case 0:
for (int j = 0; j < 13; j++) {
deck[j] = new Card("hearts", "" + j);
case 1:
for (int j = 0; j < 13; j++) {
int c = 14;
deck[c] = new Card("Club", "" + "" + j);
c++;
case 2:
for (int j = 0; j < 13; j++) {
int c = 27;
deck[c] = new Card("Diamond", "" + j);
c++;
case 3:
for (int j = 0; j < 13; j++) {
int c = 40;
deck[c] = new Card("spade", "" + j);
c++;
public void showDeck() {
for (int j = 0; j < deck.length; j++) {
System.out.println(deck[j].toString());
public static void main(String[] args) {
Game spel1 = new Game();
spel1.vulArray();
spel1.showDeck();
-
I was given an object model generated by an apache product, Axis. The generated java files use the Java Array in the following fashion:
Class Zoo {
private ArrayOfAnimals animals;
// ⦠public get/set methods cut
Class ArrayOfAnimals {
private Animal animals[];
// ⦠public get/set methods cut
Class Animal {
private String name;
// ⦠public get/set methods cut
I was tasked with mapping the one-to-many relationship between zoo and an array of animals using the Animal array. I canât find a mapping in TopLink to do this type of association. I am NOT allowed to modify the generated source code. I may be able to extend the generated classes, and perhaps provide a different superclass.
I am allowed to create the relational model for these domain classes. Can anyone help with this type of mapping?
ThanksTopLink does not directly support arrays as the mapping type for a collection, only collection types that support the Collection and Map interfaces.
In general it seems odd to use an array instead of a Java collection which would be much more efficient (in terms of adding and removing) and much more functional. I would definitely suggest changing the generated code, or the way the code is generated if at all possible.
The easiest way to map the array in TopLink would be the use get/set methods for the 1-m mapping on the Zoo class that converted the array to/from a Collection.
i.e. something like,
public List getAnimalsList() {
return new Arrays.asList(animals.animals);
public void setAnimalsList(List list) {
animals.animals = (Animal[]) list.toArray();
In general TopLink uses its ContainerPolicy class to handle collections. It may also be possible (but advanced) to write a custom container policy for your 1-m mapping that handles arrays. -
How to call a C sort function to sort a Java Array.
My name is David, I'm interning this summer doing some High Performance Computing work. I'm significantly out of my comfort zone here; I am primarily a network/network security geek, not a programming guy. I took one Java based class called problem solving with programming where we wrote like 3 programs in Java and did everything else in pseudocode and using a program called Alice http://www.alice.org/ to do things graphically. Learned basically no actual programming syntax. Also have done some self-taught perl, but only through one book and I didn't finish it, I only got about half way through it. So my expertise in programming are pretty much null.
That being said, I currently am tasked with having to figure out how to make JNI work... specifically at this time I am tasked with writing an array in Java, and designing a C program that can be called by means of JNI to sort the array. I have chosen to work with the Merge Sort algorithm. My method of coding is not one where I write the entire thing from scratch, I don't particularly have a need to master languages at this point, rather I just need to make them work. I am interested in learning, but time is of the essence for me right now. So thus far what I have done is take sample codes and tweak them to meet my purpose. However, I currently am unable to make things work. So I am asking for help.
I am going to paste 3 codes here, the first one will be my basic self-written instructions for JNI (Hello World Instructions), the second one will be my Java Array, and the third one will be my MergeSort function. I am not asking for you to DO my work for me by telling me how to manipulate my code, but rather I am asking for you to send me in the direction of resources that will be of some aid to me. Links, books (preferrably e-books so I don't have to go to a library), anything that you can send my direction that may help will be deeply appreciated. Thanks so much!
JNI Instructions:
/*The process for calling a C function in Java is as follows:
1)Write the Java Program name. Eg. HelloWorld.java
2)Compile it: javac HelloWorld.java
3)Create a header file: javah -jni HelloWorld
4)Create a C program eg. HelloWorld.java
5)Compile the C program creating a shared library eg. libhello.so (My specifc command is cc -m32 -I/usr/java/jdk1.7.0_05/include -I/usr/java/jdk1.7.0_05/include/linux -shared -o libhello.so -fPIC HelloWorld.c
6) Copy the library to the java.library.path, or LD_LIBRARY_PATH (in my case I have set it to /usr/local/lib.
7)Run ldconfig (/sbin/ldconfig)
8)Run the java program: java HelloWorld. */
//Writing the code:
//For the HelloWorld program:
//In java:
//You need to name a class:
class HelloWorld {
//You then need to declare a native method:
public native void displayHelloWorld();
//You now need a static initializer:
static {
//Load the library:
System.loadLibrary("hello");
/*Main function to call the native method (call the C code)*/
public static void main(String[] args) {
new HelloWorld().displayHelloWorld();
//In C:
#include <jni.h> //JNI header
#include "HelloWorld.h" //Header created by the javah -jni command parameter
#include <stdio.h> //Standard input/output header for C.
//Now we must use a portion of the code provided by the JNI header.
JNIEXPORT void JNICALL
Java_HelloWorld_displayHelloWorld(JNIENV *env, jobject obj)
//Naming convention: Java_JavaProgramName_displayCProgramName
printf("Hello World!\n");
return;
}Java Array:
class JavaArray {
private native int MergeSort(int[] arr);
public static void main(String[] args)
int arr[] = {7, 8, 6, 3, 1, 19, 20, 13, 27, 4};
static
System.loadLibrary("MergeSort");
}Hacked and pieced together crappy C Merge Sort code:
#include <jni.h>
#include <stdio.h>
#include "JavaArray.h"
JNIEXPORT jint JNICALL
Java_JavaArray_MergeSort(JNIEnv *env, jobject obj, jintArray arr[],jint low,jint mid,jint high)
jint i,j,k,l,b[10];
l=low;
i=low;
j=mid+1;
while((l<=mid)&&(j<=high))
if(arr[l]<=arr[j])
b=arr[l];
l++;
else
b[i]=arr[j];
j++;
i++;
if(l>mid)
for(k=j;k<=high;k++)
b[i]=arr[k];
i++;
else
for(k=l;k<=mid;k++)
b[i]=arr[k];
i++;
for(k=low;k<=high;k++)
arr[k]=b[k];
void partition(jint arr[],jint low,jint high)
jint mid;
if(low<high)
mid=(low+high)/2;
partition(arr,low,mid);
partition(arr,mid+1,high);
sort(arr,low,mid,high);You're doing OK so far up to here:
Java_JavaArray_MergeSort(JNIEnv *env, jobject obj, jintArray arr[],jint low,jint mid,jint high)This is not correct. It is not what was generated by javah. It would have generated this:
Java_JavaArray_MergeSort(JNIEnv *env, jobject obj, jintArray arr,jint low,jint mid,jint high)A 'jintArray' is already an array, embedded in an object. You don't have an array of them.
So you need to restore that, and the header file, the way 'javah' generated them, then adjust your code to call GetIntArrayElements() to get the elements out of 'arr' into a local int[] array, sort that, and then call ReleaseIntArrayElements() to put them back. -
Passing hard coded array to a method
how to passing hard coded array to a method
like method1("eee","eoe","eee",.....)
which should populate a array of strings (say arr[]) for the method
what can be done??or if you're using Java 5.0 declare the method aspublic void method(String... array) {
} -
Hi,
How can I create an empty object array in Java?
Thanks
gObject object[] = new Object[len]; //len is an
Integer-value for the length of the arrayThat's right.. -
How to declare normal java array in fx
How can we declare normal java array in fx. lets say I extend an abstract java class and it has a method which takes String array as parameter: abstract public void met(String[] users) ;How can i declare String[] parameter while overriding this abstract method in javafx. This does not work: override public function met(s:String[]){ ... }
Hi,
The code below works for me:
public function run(args:String[]){
var s:String[] = ["Hi", "Hello", "Love", "Peace"];
var t:Test2 = Test2{};
t.met(s);
public abstract class Test{
public abstract function met(s:String[]):Void;
class Test2 extends Test{
public override function met(s:String[]):Void{
for(x in s){
println(x);
}[]'s -
Problems creating a Java Array using JNI-HELP!
Hi,
I am trying to create a Java Array using JNI.I have posted the code below. The problem is that the oth element is added correctly to the Array but when the JVM gets to the next element...it goes for a toss. It is not able to create a new instance of the object in GetUGEntity() function...there seems to be some problem in creating a new instance of the object!
Can somebody help me with this?
jobject GetUGEntity(JNIEnv *env, UF_DISP_j3d_entity_t* entity_list)
int numVerts=0, numStrips=0;
jfieldID fid;
jdoubleArray jTransform=NULL;
jstring jstrName=NULL;
jdoubleArray jNormals=NULL;
//Init an Entity object
cout<< "**Getting New Class Reference...";
jclass jEntity = env->FindClass("Lcom/wipro/java3d/rmi/Entity;");
cout << "**got Class reference..."<<endl;
if (jEntity == NULL)
return NULL;
cout<<"Creating new object instance...";
jmethodID mIDInit = env->GetMethodID(jEntity, "<init>", "()V");
cout<<"Got java method id...";
jobject javaObj = env->NewObject(jEntity, mIDInit);
if (javaObj==NULL)
return NULL;
cout << "Created!" << endl;
//Entity ID
cout<< "**Setting eid...";
fid=env->GetFieldID(jEntity,"eid","I");
jint eid = (jint)(entity_list)->eid;
env->SetIntField(javaObj, fid, eid);
//env->DeleteLocalRef(eid);
cout << "Done!" << endl;
cout << "Done!" << endl;
cout<< "**Returning jobject...";
return javaObj;
jobjectArray createJArray(JNIEnv* env, UF_DISP_j3d_entity_t** entity_list, int noOfEntities )
UF_DISP_j3d_entity_t* tempVar=NULL;
cout<<"*Creating Jobjectarray...";
jobjectArray jEntityArray = (jobjectArray) env->NewObjectArray(noOfEntities,
env->FindClass("Lcom/wipro/java3d/rmi/Entity;"),NULL);
cout<<"Created!"<<endl;
for(int i=0; i<noOfEntities;++i)
tempVar = &(*entity_list);
if (tempVar !=NULL)
cout<<"*Trying to get Entity...."<<endl;
jobject jEntity = GetUGEntity(env, tempVar);
if (jEntity!= NULL)
cout<<"Got Entity!" <<endl;
cout <<"*Setting Array Element....";
env->SetObjectArrayElement(jEntityArray, i, jEntity);
cout << "Done!" << endl;
else
printf("ERROR: Did not get Entity Reference");
else
printf("ERROR: Got a NULL Reference!");
return jEntityArray;Hi Deepak,
Could you please let us know upto which line your code is going safe. Try printing the value in the structure before you send that to the method GetUGEntity().
I am not too sure that would be a problem. But I have faced a problem like this, wherein I tried to access a structure for which I have not allocated memory and hence got exception because of that.
Since your JNI code seems to be error free, I got doubt on your C part. Sorry.
Dhamo. -
How do I pass an array to a method?
Hopefully you guys don't mind answering one of my stupid questions :o(
I have problem passing an array to a method.
//Here is the code that calls to the method:
String[] Folder = new String[19];
int cnt;
for(cnt=0; cnt<20; cnt++){
Folder[cnt] = request.getParameter("searchfolder_name" + (cnt + 1));
ProcessNotify(Folder[cnt]);
//================================================================
//Here the the method that is supposed to take in the array
private void ProcessNotify(String FolderName[]){
FolderName = new String[19];
int cnt;
for(cnt=0; cnt<20; cnt++){
System.out.println("Folder Name: " + FolderName[cnt]);
I got an error that says java.lang.String[] can not be applied to java.lang.String
I thought "String FolderName[]" is an array? Anyway... I'm confused. If you know the answer, plz let me know :o) big thx
lilProcessNotify(Folder[cnt]);
Are you trying to pass the whole array or just one piece from it? What you coded, tried to pass just one piece by specifying a subscript. BTW variable cnt is a subscript out of range.
If you meant to pass the whole array, just use it's name with no subscript. -
I guess I'll show you what I am trying to do rather and then explain it
public class arraycalc
int[] dog;
public void arraycalc()
dog = new int[2];
public void setSize(int size)
dog[1] = size;
public int getSize()
return dog[1];
This gives me a null pointer exception...
How can I use my array from other methods?You have to make the array static. :)
Although I must admit, this is rather bad usage. What you want to do is use an object constructor to make this class an object type, and then create the array in your main class using this type, and then call the methods from this class to modify your array. Creating the array inside the other method leads to a whole bunch of other stuff that's ... well, bad. :)
Another thing: Because you're creating your array inside this class and you want to call your array from another class, you need to make the array static; to make it static, you must make your methods static. And according to my most ingenious computer science teacher, STATIC METHODS SUCK. :D
So, if you want to stick with your layout, it would look like:
public class arraycalc
static int[] dog;
public static void arraycalc()
dog = new int[2];
public static void setSize(int size)
dog[1] = size;
public static int getSize()
return dog[1];
}But I must warn you, that is absolutely horrible code, and you shouldn't use it. In fact, I don't even know why I posted it.
You should definitely read up on OOP, as this problem would be better solved by creating a new object type.
Maybe you are looking for
-
IPad mini acting strange. Apps open and close randomly. Any ideas?
My iPad mini acts strange. Apps will randomly open and close and I have no control over it. I have reset it to factory and started all over but it is still doing it. Any ideas on what I should do?
-
CSV Export Report: Set Enclosed By to null
Hi, I need to export a report in csv with the "Enclosed By" as being null. ie: 1,2,3 rather than "1","2","3" Any ideas? I tried using a space but we can't have a space, it really needs to be null. Thank you, Martin [http://apex-smb.blogspot.com/]
-
Hi , Can anyone Please provide me good Questionaries about HR ABAP. Thanks in Advance, PAVAN.
-
Trackpoint driver works differently than the older one
I made the jump recently from Vista 32 to 64 and after installing drivers i noticed that i can no longer tap the trackpoint instead of left click - have you guys noticed that ?
-
Can't show signatures on compose page
signature pop up menu on compose page does not change from "none" after sigs created.