标签:
关于android JNI的讲解网络上已经很多了,这里贴出自己的实践步骤,加深印象。
1)编写java代码,并通过javac JniFuncMain.java编译class文件:
public class JniFuncMain{
private static int staticIntFiled = 300;
static{
System.loadLibrary("jnifunc");
}
public static native JniTest createJniObject();
public static void main(String[] args){
System.out.println("java CreateJniObject()调用本地方法");
JniTest jniObj = createJniObject();
jniObj.callTest();
}
}
2)通过javah JniFuncMain生成C/C++的.h头文件
3)参考.h头文件的方法头 写 C/C++文件,jnifunc.cpp代码:
#include "JniFuncMain.h"
#include <stdio.h>
JNIEXPORT jobject JNICALL Java_JniFuncMain_createJniObject
(JNIEnv *env, jclass clazz){
jclass targetClass;
jmethodID mid;
jobject newObject;
jstring helloStr;
jfieldID fid;
jint staticIntFiled;
jint result;
fid = env->GetStaticFieldID(clazz,"staticIntFiled","I");
staticIntFiled = env->GetStaticIntField(clazz,fid);
printf("cpp| 获取staticIntFiled \n");
printf("staticIntFiled is %d\n",staticIntFiled);
targetClass=env->FindClass("JniTest");
mid=env->GetMethodID(targetClass,"<init>","(I)V");
printf("CPP| 生成JniTest 对象");
newObject = env->NewObject(targetClass,mid,100);
mid =env->GetMethodID(targetClass,"callByNative","(I)I");
result =env->CallIntMethod(newObject,mid,200);
fid =env->GetFieldID(targetClass,"intFiled","I");
printf("CPP| 设置JniTest对象的intFielid的200\n");
env->SetIntField(newObject,fid,result);
return newObject;
}
4)通过C++编译工具生产链接库。如果没安装环境的话需要下载Visual C++ 2008 Express Edition。
安装完之后使用在Microsoft Visual Studio 9.0\VC\bin下的cl.exe 来生成dll,
标签:
原文地址:http://www.cnblogs.com/yemanling/p/4435117.html