0

I want to return an object from c++ to java code using JNI.
I don't need to use its methods, but just read its fields. How can I do it?
This class is just something like this:

class MyOutputClass
{
public:
 Array<SomeOtherClass> m_objects1;
 Array<YetAnoterClass> m_objects2;
}

Array is a class of mine, but i'll use the java array instead :)

Idov
  • 5,006
  • 17
  • 69
  • 106
  • Depends on the object. It likely needs to be a [POD (or standard-layout in C++11)](http://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special) for this. Show us some code. – R. Martinho Fernandes Aug 27 '11 at 15:47
  • ok, I added some code. I don't have much JNI code yet :) – Idov Aug 27 '11 at 17:34

2 Answers2

2

If you want to pass a C++ object to Java you can't. But you can create a Java object in native and then return this from your native method.
That would be done like this:

JNIEXPORT myJavaObj JNICALL Java_cls_getObj
(JNIEnv *env, jobject obj)
{
jclass myClass;

//Find your class
myClass = (*env)->FindClass(env, "()LMyJavaClass;");

jmethodID cons = env->GetMethodID(myClass, "<init>", 
                              "(V)V"); 
jobject obj = env->NewObject(myClass, cons);

//Return the object.
return obj;
}

You can either pass your data in the ctor or access the fields of your object and change them. BTW. I did not compile the code above. But it should not contain too many errors.

mkaes
  • 13,781
  • 10
  • 52
  • 72
  • ok, but where is this JNI object should be defined? in the C++ code? – Idov Aug 27 '11 at 17:29
  • @ldov: No this is a java object. In the example you search a Java class find the ctor and then execute the ctor aka create a new object. Then you return it back to the java part and can use it in there. Maybe you should take a look at the JNI tutorial. http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html – mkaes Aug 28 '11 at 14:14
0

Won't something like http://code.google.com/p/protobuf/ or http://msgpack.org/ do the job for you? The idea is to create server/client in your java/c++ code and start moving objects around? The overall communication is pretty efficient so I doubt speed to be an issue.

LordDoskias
  • 3,121
  • 3
  • 30
  • 44