NDK 入门(二):C 与 JAVA 互相调用 demo

编译方法参见前一篇博文。

这里主要写给个demo 展示 C与Java 互相调用的方法,  功能比较没有意义,就是Java 调用 C, C 里面的函数再反过来调用Java。

Java 工程:

package com.ndk;

import java.security.PublicKey;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class NdkAdvanceActivity extends Activity {
    private TextView mTextView;
    private StringBuilder mStringBuilder;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView) findViewById(R.id.text);
        mStringBuilder = new StringBuilder();
        setTestView();
        
    }
    
    public void setTestView() {
        mStringBuilder.append(JavaCallC()).append("\n");
        mTextView.setText(mStringBuilder.toString());
    }
    
    
    public void cCallJava() {
        mStringBuilder.append("C Call Java Success!").append("\n");
    }
    
    public native String JavaCallC();
    static {
        System.loadLibrary("ndk-advance");
    }
    
}


C 代码 :

#include <string.h>
#include <jni.h>


jstring JNICALL Java_com_ndk_NdkAdvanceActivity_JavaCallC
  (JNIEnv *env, jobject obj)
{
    jclass cls;
    jmethodID mid;
    cls = (*env)->GetObjectClass(env, obj);
    mid = (*env)->GetMethodID(env, cls, "cCallJava", "()V");
    (*env)->CallVoidMethod(env, obj, mid);
    return (*env)->NewStringUTF(env, "Java Call C success!");
}

Android.mk :
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := ndk-advance
LOCAL_SRC_FILES := ndk-advance.c

include $(BUILD_SHARED_LIBRARY)



你可能感兴趣的:(java,c,String,Module,include,library)