在您的 Android 根应用程序文件夹中创建一个 JNI 文件夹(其中有 src、res)。将代码 (1) 放在那里,将其命名为 someshared-lib.c。
(1)
Java_YourPackageName_YourClassNameWhereYoudeclareYourNativeFunction_NativeFuntionName(JNIEnv* env,jobject thiz)
{
//your c code , the JNI will act as a wrapper for it
return (*env)->NewStringUTF(env, "<string to pass or you can mention jchar * type string >");
}
(2)输入java文件
package YourPackageName;
public class YourClassNameWhereYoudeclareYourNativeFunction extends Activity
{
public native String NativeFuntionName();
String returnValue = NativeFuntionName();
}
(3)在 Android.mk 中这样做:
LOCAL_PATH := $(call my-dir)
包括 $(CLEAR_VARS)
LOCAL_MODULE := someshared-lib //注意libname和c文件名一样
LOCAL_SRC_FILES := someshared-lib.c //这是您放置代码的文件 (1)
包括 $(BUILD_SHARED_LIBRARY)
导出您的 ndk-build
(导出 PATH=:$PATH
转到上面创建的 JNI 文件夹:
执行 ndk-build 命令
您将在应用程序根文件夹中形成的 lib 文件夹中获得一个形成的库 someshared-lib。在构建和运行应用程序时,这将与apk 并将安装在设备中。要验证这一点,您可以转到
/data/data/your_package_name/lib 文件夹。
应用程序在 /data/data/your_package_name/lib(也包括 /system/lib)文件夹中搜索了此库,并将其用于 Android 应用程序进行的动态调用 (JNI)。
现在如果你想返回字符串以外的任何内容,你必须在 c 文件中更改上述方法声明,如下所示:
Java_YourPackageName_YourClassNameWhereYoudeclareYourNativeFunction_NativeFuntionName(JNIEnv* env,jclass obj,jobject thiz)
{
jfieldID fid;
jboolean enable_flag;
//Pass the class object having all the variable from the android app to the JNI in the jclass obj and access its members using the field ID and using Get and Set firld ID.
clazz = (*env)->GetObjectClass(env, info);
fid = (*env)->GetFieldID(env,clazz,"some_variable","X"); //"X" - type of variable for boolean it //is Z , for INtezer it is I, for double it is D,
详情请参考document
//for getting teh value fomr the JNI
enable_flag = (*env)->GetBooleanField(env, **thiz**, fid);
//for setting the value
fid = (*env)->GetFieldID(env,clazz,"other_float_variable","D");
(*env)->SetDoubleField(env,**thiz**,fid,other_float_variable);
}
此外,在 Android 应用程序中,您必须传递结构的 Class 对象。
例如
(2) 现在将变为:
打包YourPackageName;
public class YourClassNameWhereYoudeclareYourNativeFunction extends Activity
{
public native String NativeFuntionName();
String returnValue = NativeFuntionName( exampleStruct exst);
示例结构:
公共类exampleStruct {
protected boolean some_variable = 0;//no log saving by default
protected float other_float_variable = 0;
}
}
希望这会有所帮助。