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

2
  • Depends on the object. It likely needs to be a POD (or standard-layout in C++11) for this. Show us some code. Commented Aug 27, 2011 at 15:47
  • ok, I added some code. I don't have much JNI code yet :) Commented Aug 27, 2011 at 17:34

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok, but where is this JNI object should be defined? in the C++ code?
@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. java.sun.com/developer/onlineTraining/Programming/JDCBook/…
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.