dcsimg
Passing an Array of objects
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Wednesday, July 31, 2002 11:03 PM

I have been trying to pass an array of objects from java to C. They are simple objects, only fields, no methods. Example... class User { String name; int id; } public class JNIExample { User[] users = new User[10]; public native void nativeCode(User[] usersarray); static { try{ System.loadLibrary("object"); }catch(Exception e) { System.out.println("Could not load library."); } } public static void main(String[] args) { JNIExample anex = new JNIExample(); anex.nativeCode(anex.users); } }    More>>

I have been trying to pass an array of objects from java to C. They are simple objects, only fields, no methods.
Example...


			
class User
{
String name;
int id;
}

public class JNIExample
{
User[] users = new User[10];

public native void nativeCode(User[] usersarray);

static
{
try{
System.loadLibrary("object");
}catch(Exception e)
{
System.out.println("Could not load library.");
}
}

public static void main(String[] args)
{
JNIExample anex = new JNIExample();
anex.nativeCode(anex.users);
}
}





Could someone give me sample code on how to access the array elements and get/set the object values on the C side.

Thanks

Maurice    <<Less

Re: Passing an Array of objects

Posted By:   Alexander_Krapf  
Posted On:   Thursday, August 8, 2002 08:10 AM

Maurice,


You need to use the GetObjectArrayElement/SetObjectArrayElement methods for that purpose. These methods will give you access to the object elements of your array and then you will still have to use the JNI methods to access the fields of these elements.


A simpler way to do this would be to use JunC++ion. JunC++ion allows you to generate C++ proxy classes for existing Java classes plus native method implementations that delegate to C++-style methods.


You would end up writing something like:



{
//users is the argument being passed as type User::array1D
if( users == null )
throw IllegalArgumentException( "users was null" );

for( int i=0; users.length; i++ )
{
String name = users[ i ].name;
int age = users[ i ].age;

//use the data natively...
}
}


Notice that this is C++ code, not Java code, yet it's as readable and maintainable as your Java code.
Check it out.


Regards,


Alex

About | Sitemap | Contact