简体   繁体   English

JNI pass java base64 string to C++ and return base64 string to java

[英]JNI pass java base64 string to C++ and return base64 string to java

Hello im building a android app using JNI and im trying to pass a base64 string to c++, and then return a base64 string.您好,我正在使用 JNI 构建 android 应用程序,并且我试图将 base64 字符串传递给 c++,然后返回 Z95A1446A712ABB7E4AF5 字符串。 Im using a javax.crypto.Cipher library to encrypt a base64 string, and send that string to c++, and use that string with c++.我使用 javax.crypto.Cipher 库加密 base64 字符串,并将该字符串发送到 c++,并将该字符串与 c++ 一起使用。 But for some reason when I pass that string to JNI, its not showing.但是由于某种原因,当我将该字符串传递给 JNI 时,它没有显示。 My code snippet is below..我的代码片段如下..

enter code here  

//MyJobService.java
public class MyJobService  extends JobService
{
   NativeLibrary ni = new NativeLibrary();
   
   public void httpRequest()
   {
         AES128 encrypted = AES128.encrypt("MyKey", String.valueOf("My input string"));
         ni.request(encrypted.toString())
   }
} 

//NativeLibrary.java
public class NativeLibrary extends AsyncTask<String, Void, String> 
{
      static {
          System.loadLibrary("native-lib");
     }
       public native String request(String encryptStr);
}

//native-lib.cpp
 extern "C" JNIEXPORT jstring JNICALL Java_com_example_mobileapp_NativeLibrary_request(JNIEnv *env,jobject 
 instance, jstring encStr)
   {
         __android_log_write(ANDROID_LOG_DEBUG, "ENC_STRING", (char *) encStr);
        // .. do something
        return (char *) encStr;
   }

JNIENVInterface exposes set of function table to retrieve the arguments passed from JAVA front. JNIENVInterface 公开一组 function 表以检索从 JAVA 前面传递的 arguments。 https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

In your case, you need to use GetStringUTFChars() to read the jstring from Java -在您的情况下,您需要使用 GetStringUTFChars() 从 Java 读取 jstring -

//native-lib.cpp
extern "C" JNIEXPORT jstring JNICALL 
Java_com_example_mobileapp_NativeLibrary_request(JNIEnv *env,jobject 
instance, jstring encStr)
    {
      char *utfString = (char *) (env)->GetStringUTFChars(encStr, NULL);
      __android_log_print(ANDROID_LOG_DEBUG, "ENC_STRING = %s", utfString);
          // .. do something
      return env->NewStringUTF(utfString);//modified string returned
    }

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

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