简体   繁体   English

Android将char数组发送到JNI C ++

[英]Android send char array to JNI c++

Good day 美好的一天

I have a question how to send my char array to jni c++ code? 我有一个问题如何将我的char数组发送到jni c ++代码? I know how send int number only.. 我知道如何只发送int号码。

A have this array char[] chars = password.toCharArray(); 具有此数组char[] chars = password.toCharArray();

and private native void JNIEncrypt(char[] chars); private native void JNIEncrypt(char[] chars);

My JNI method look like this 我的JNI方法看起来像这样

Java_com_kru13_ndkdemos_MainActivity_JNIEncrypt( JNIEnv* env, jobject  obj, ?????)

I would like to ask how it should look JNI method? 我想问一下它应该怎么看JNI方法? I need use char array in c++ code 我需要在C ++代码中使用char数组

than you 比你

It would be: 这将是:

Java_com_kru13_ndkdemos_MainActivity_JNIEncrypt( JNIEnv* env, jobject  obj, jcharArray array)

Inside the function you will have to use env->GetCharArrayElements(...) . 在函数内部,您将必须使用env->GetCharArrayElements(...)

Why not just pass it as a String , which is jstring in JNI: 为什么不将其作为String传递,在JNI中为jstring

// Java side
private native void JNIEncrypt(String password);

// Native JNI side
Java_com_kru13_ndkdemos_MainActivity_JNIEncrypt(JNIEnv* env, jobject thiz, jstring password);

You can then access the string JNI side via GetStringChars () and related or GetStringUTFChars (). 然后,您可以通过GetStringChars ()和相关或GetStringUTFChars ()访问字符串JNI端。 For example: 例如:

const char* utf8 = env->GetStringUTFChars(password, NULL);
// do something with utf8
env->ReleaseStringUTFChars(password, utf8);

toCharArray gets you the sequence of Unicode/UTF-16 code-units from the string. toCharArray从字符串中获取Unicode / UTF-16代码单元的序列。 On Android, You will probably want Unicode/UTF-8 on the C++ side, but that depends on the C++ libraries you want to use. 在Android上,您可能希望在C ++端使用Unicode / UTF-8,但这取决于要使用的C ++库。 Once, you know, use the Java String class to get the bytes. 一旦知道,就可以使用Java String类来获取字节。

Note: GetStringUTFChars gives you modified UTF-8 code-units, which Unicode-compliant libraries reject for many characters. 注意: GetStringUTFChars为您提供了已修改的UTF-8代码单元,兼容Unicode的库拒绝许多字符。

private void JNIEncrypt(String string) {
    JNIEncrypt(string.getBytes("UTF-8")); 
    // Or, for the OS default, string.getBytes()
}

private native void JNIEncrypt(byte[] chars);

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

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