Idov
Idov

Reputation: 5124

Returning objects from C++ to Java

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 :)

Upvotes: 0

Views: 2665

Answers (2)

LordDoskias
LordDoskias

Reputation: 3191

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.

Upvotes: 0

mkaes
mkaes

Reputation: 14119

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.

Upvotes: 2

Related Questions