Create a project with "File" "New" "New Projekut" of Android Studio.
This time I want to call C from Java, so select "Native C ++" and click "Next" to go to the next screen
Name is appropriate this time "test01"
Specify the project directory to be created this time with Save location
Language is created in "Java", and when the settings are complete, click "Next" to display the next screen.
Here, simply select "Finish".
(On this screen, you can set to use C ++ 11 or C ++ 14, but you can set it later, so ignore it)
When such a screen appears, I was able to create a project for the time being.
■ Setp2: Java to CAdd the function "testFunc" called from C to [MainActivity.Java].
MainActivity.java
package l.toox.test01;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Example of a call to a native method
        TextView tv = findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    public void testFunc(){
    }
}
Next, the part that reads Java from C. Modify [Native-lib.cpp] as follows.
native-lib.cpp
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
tugini 
        JNIEnv *env,
        jobject in_thiz) {
    jobject my_class = env->NewGlobalRef(in_thiz);
    jclass clazz = env->GetObjectClass(my_class);
    jmethodID mobj = env->GetMethodID( clazz, "testFunc", "()V" );
    env->CallVoidMethod( my_class, mobj );
    env->DeleteLocalRef( clazz );
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}
(Note that the argument is jobject in_thiz.)
If you run it with this, you are calling Java from C.
Breaks can be seen during debug execution.
Recommended Posts