Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JNI function call to return an object?  RSS feed

 
Meenal Srivastva
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is it possible to create a c++ DLL method that returns a complex type( object instead of the usual int etc.).
I want to receive such an object in a Java object like this:
Object receivedObject=myClassObj.dllMethod("some string");

Any pointers ?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JNI code can create and return Java objects easily; you just use the JNI API to create and initialize the object.

You could also return a pointer to a C++ object; you'd just cast it to an int or long and return that. The Java code couldn't do anything directly to that pointer, though -- just store it. You'd need more JNI methods if you wanted the Java code to be able to directly invoke methods of the C++ object.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like Ernest said, you can create objects with native code with JNI. The procedure:
- Get a reference to the object's class, e.g. by using FindClass
- Get a reference to the object's constructor you want to use, by using GetMethodID. The method name is "<init>".
- Call one of the NewObjectX methods, e.g. NewObjectA

The return value of the last method will be the newly created object.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
You could also return a pointer to a C++ object; you'd just cast it to an int or long and return that.


That doesn't sound very portable. JNI code ought to be portable, whenever possible. You never know when someone may ask you to make an implementation on a new platform.

A simple way to do this would be to call the C++ thing a "handle", not a "pointer", and declare its size as either int (4 bytes) or long (8 bytes). On platforms where a pointer would fit in that size, the C++ code could typedef the handle to be a pointer. On other platforms, the C++ code could implement some kind of mapping between handles and pointers. The important thing is that the interface between the C++ and Java code shouldn't talk about pointers.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!