简体   繁体   English

如何将字符串数组从 C++ 返回到 Java (JNI)

[英]How to return String Array from C++ to Java (JNI)

i have a String array on c++ and i need to return it to the Java class.我在 C++ 上有一个 String 数组,我需要将它返回给 Java 类。 How can i do this?我怎样才能做到这一点?

I have tried this:我试过这个:

string paroleord[app.size()];
jobjectArray ret;
ret = (jobjectArray)env->NewObjectArray(app.size(),env->FindClass("java/lang/String"), 0);
for (int k = 0; k < app.size(); k++)
{
    env->SetObjectArrayElement(ret, k,env->NewStringUTF(paroleord[k]));
}

return ret;

But i have an error because NewStringUTF needs an object as parameter, can you help me please?但是我有一个错误,因为 NewStringUTF 需要一个对象作为参数,你能帮我吗?

If you can survive with Vector or Array you can simply return collection from C++ code. 如果你可以使用VectorArray生存,你可以简单地从C ++代码返回集合。

It will require some "low level" coding, but it's fairly straightforward. 它需要一些“低级”编码,但它相当简单。

Take a look here: 看看这里:

http://jnicookbook.owsiak.org/recipe-no-045/ http://jnicookbook.owsiak.org/recipe-no-045/

as for the String itself, take a look here: 至于String本身,看看这里:

http://jnicookbook.owsiak.org/recipe-No-010/ http://jnicookbook.owsiak.org/recipe-No-010/

Also, make sure to convert string to array of characters. 此外,请确保将string转换为字符数组。

(*env)->NewStringUTF(env, my_string.c_str());

You can use Scapix Java Link C++ JNI library to automatically convert between many C++ and Java types. 您可以使用Scapix Java Link C ++ JNI库在许多C ++和Java类型之间自动转换。 Here is an example : 这是一个例子

#include <scapix/java_api/java/lang/System.h>
#include <scapix/java_api/java/util/Locale.h>
#include <scapix/java_api/java/text/DateFormatSymbols.h>

using namespace scapix::link::java;
using namespace scapix::java_api;

void test1()
{
    // C++ objects are automatically converted to and from corresponding Java types.
    // This works for any type supported by scapix::link::java::convert() interface,
    // which supports many STL types and can be extended for your own types.

    std::string version = java::lang::System::getProperty("java.version");
    std::vector<std::string> languages = java::util::Locale::getISOLanguages();
    std::vector<std::vector<std::string>> zone_strings = java::text::DateFormatSymbols::getInstance()->getZoneStrings();
    std::map<std::string, std::string> properties = java::lang::System::getProperties();
}

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

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