简体   繁体   English

将对象从C ++返回到Java

[英]Returning objects from C++ to Java

I want to return an object from c++ to java code using JNI. 我想使用JNI将对象从c ++返回到Java代码。
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 :) 数组是我的一类,但我将改用Java数组:)

If you want to pass a C++ object to Java you can't. 如果要将C ++对象传递给Java,则不能这样做。 But you can create a Java object in native and then return this from your native method. 但是您可以在本机中创建一个Java对象,然后从本机方法中返回该对象。
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. 您可以在ctor中传递数据,也可以访问对象的字段并进行更改。 BTW. 顺便说一句。 I did not compile the code above. 我没有编译上面的代码。 But it should not contain too many errors. 但是它不应包含太多错误。

Won't something like http://code.google.com/p/protobuf/ or http://msgpack.org/ do the job for you? 不会像http://code.google.com/p/protobuf/http://msgpack.org/这样的产品吗? The idea is to create server/client in your java/c++ code and start moving objects around? 这个想法是在Java / C ++代码中创建服务器/客户端并开始移动对象? The overall communication is pretty efficient so I doubt speed to be an issue. 总体沟通效率很高,因此我怀疑速度是否会成为问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM