问题描述
我目前在项目中使用C ++和Java,我想能够将包含在C ++中的对象发送到我的Java接口,以便通过GUI修改它,然后将修改发回在C ++中。
到目前为止,我已经通过JNI接口向Java返回了任何内容,一个int或一个布尔值。这一次我必须通过接口发送一个对象。我已经在C ++和Java中提供类似的类定义。 我想知道如何创建对象,以便我可以在Java中使用它。
在C ++中:
JNIEXPORT MyObject JNICALL Java_ca_X_Y_Z_C_1getMyObject(JNIEnv * env,jclass,jint number);
此函数将被Java调用,以便从C ++端获取对象包含在单例中,容易访问)。
在Java端,我对这个方法进行一个简单的调用,
MyObject anObject = C_getMyObject(3);
应返回新创建的对象。
当我进行实际调用时,Java目前返回一个UnsatisfiedLinkError。
这里是我选择使用的解决方案:
(C ++)
clazz = env- > FindClass(java / lang / Integer);
jmethodID method = env-> GetMethodID(clazz,< init>,(I)V);
return env-> NewObject(clazz,method,(jint)anInteger);
但是我意识到这不是很便携,有点太复杂了。
相反,我决定返回一个字符串,Java会解析并使用它来初始化对象。
(JAVA)
String aString =valuesoftheobject;
MyObject myObject(aString);
MyObject将有一个构造函数接受一个字符串。我相信解决方案简单有效。
I'm currently using both C++ and Java in a project and I'd like to be able to send an object which is contained in C++ to my Java interface in order to modify it via a GUI and then send the modification back in C++.
So far I've been returning either nothing, an int or a boolean to Java via the JNI interface. This time I have to send an object through the interface. I have made similar class definition available both in C++ and in Java. I'd like to know how I'd go about creating the object so that I can use it in Java.
In C++ I have:
JNIEXPORT MyObject JNICALL Java_ca_X_Y_Z_C_1getMyObject(JNIEnv* env, jclass, jint number);
This function would get called by Java in order to get the object from the C++ side (the object is contained in a singleton, easily accessible).
On the Java end, I do a simple call to this method,
MyObject anObject = C_getMyObject(3);
which should return me the newly created object.
Java currently returns me a UnsatisfiedLinkError when I do the actual call. What is wrong?
Here's the solution I opted to use:
First, I would create a similar object in Java. Then, from C++ I would instanciate it and pass it all the values.
(C++)
clazz = env->FindClass("java/lang/Integer");
jmethodID method = env->GetMethodID(clazz, "<init>", "(I)V");
return env->NewObject(clazz, method, (jint)anInteger);
But then I realised this wasn't very portable and was a bit too complicated.
Instead, I decided to return a string that Java would parse and use to initialize the object on its side.
(JAVA)
String aString = "valuesoftheobject";
MyObject myObject(aString);
MyObject would have a constructor which takes a string. I believe the solution is simple and effective.
这篇关于通过JNI将C ++类返回到Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!