简体   繁体   中英

Sending String to C++ from Android app using JNI

I am trying to send a dynamic String , obtained from end user in Android App using JNI. Though after searching on internet for similar examples , it is quite complicated for me like a newbie to work it out.

I am sharing my code, below for each file.

MainActivity.java

public class MainActivity extends AppCompatActivity {

   static {

      System.loadLibrary("native-lib");

   }

   public native int initialize();

   // i want to send params like String from android App in the below method , what is the proper way to do it.
   // public native int sendData(String param1 , String param2);


}

native-lib.cpp

#include "jni.h"

extern "C"
JNIEXPORT jint JNICALL
Java_com_newapp_myapp_MainActivity_initialize(JNIEnv *env, jobject instance){

    activity = env->NewGlobalRef(instance);
    return my_initialize(my_jvm, activity);
}

main.h

#ifdef __cplusplus
extern "C" {
#endif

#ifndef MAIN_H
#define MAIN_H

#include "jni.h"

int my_initialize(_JavaVM*, jobject);

#endif

#ifdef __cplusplus
}
#endif

My question here is , how to send the String parameters within a method to C++ from Android. for example implementing the sendData() method in MainActivity , equivalent code for JNI file and the same for C++ file.

Note : Code is very huge that is why i have shared snippet. The code is working properly.

Assuming that your files are:

public class AppCompatActivity {

}

and

public class MainActivity extends AppCompatActivity {

   static {
      System.loadLibrary("native-lib");
   }

   public native int sendData(String param1 , String param2);

}

All you have to do follows:

> javac -h . MainActivity.java
> cat MainActivity.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class MainActivity */

#ifndef _Included_MainActivity
#define _Included_MainActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     MainActivity
 * Method:    sendData
 * Signature: (Ljava/lang/String;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_MainActivity_sendData
  (JNIEnv *, jobject, jstring, jstring);

#ifdef __cplusplus
}
#endif
#endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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