发布网友 发布时间:2022-04-24 09:46
共2个回答
热心网友 时间:2022-06-18 16:14
Android.mk文件:
LOCAL_SRC_FILES参数用空格隔开
[c-sharp] view plaincopyprint?
LOCAL_PATH:=$(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE:=native
LOCAL_SRC_FILES:=geolo.cpp my_jni.h
include $(BUILD_SHARED_LIBRARY)
2. geolo.cpp
先用FindClass方法找到java类,有点类似java的反射用LoadClass
再用CallObjectMethod方法调用Java类的函数。
[c-sharp] view plaincopyprint?
#include "my_jni.h"
jobject getInstance(JNIEnv* env, jclass obj_class){
jmethodID construction_id = env->GetMethodID(obj_class, "<init>", "()V");
jobject obj = env->NewObject(obj_class, construction_id);
return obj;
}
JNIEXPORT jstring JNICALL Java_com_easepal_geolo_CActivityMain_stringFromJNI(JNIEnv* env, jobject thiz){
jstring str;
jclass java_class = env->FindClass("com/easepal/geolo/CForCall");
if (java_class == 0){
return env->NewStringUTF("not find class!");
}
jobject java_obj = getInstance(env, java_class);
if (java_obj == 0){
return env->NewStringUTF("not find java OBJ!");
}
jmethodID java_method = env->GetMethodID(java_class, "GetJavaString", "()Ljava/lang/String;");
if(java_method == 0){
return env->NewStringUTF("not find java method!");
}
str = (jstring)env->CallObjectMethod(java_obj, java_method);
return str;
}
3. my_jni.h
[c-sharp] view plaincopyprint?
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_easepal_geolo_CActivityMain */
#ifndef _Included_com_easepal_geolo_CActivityMain
#define _Included_com_easepal_geolo_CActivityMain
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_easepal_geolo_CActivityMain
* Method: stringFromJNI
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_easepal_geolo_CActivityMain_stringFromJNI(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
4. CActivityMain.java
[c-sharp] view plaincopyprint?
package com.easepal.geolo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class CActivityMain extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText( stringFromJNI("hello") );
setContentView(tv);
}
static {
System.loadLibrary("native");
}
public native String stringFromJNI(String str);
}
5. CForCall.java
[c-sharp] view plaincopyprint?
package com.easepal.geolo;
public class CForCall{
public CForCall(){};
//public ~CForCall(){};
public String GetJavaString(){
String str;
str = "123456";
return str;
}
}
热心网友 时间:2022-06-18 16:14
这个问题可以看我的帖子“ndk java 和 c 互掉”:
http://jingyan.baidu.com/article/f54ae2fcde72be1e92b84916.html
帖子集文档,截图,视频于一体,同时包括,java调用c,c调用java,javap,javah的使用等,
希望对你有用,我是ndk吧吧主,有问题可以ndk吧留言,谢谢!