您的位置:首页 > 移动开发 > Android开发

Android ndk windows下使用环境设置与编程实例:由.java自动生成xxx.h

2013-07-16 18:13 585 查看
思路:

本文从java到c 自动生成jni的xx.h文件

在eclipse中创建好xx.java文件,然后编译在相应的bin目录下生成xx.class文件,要生成xx.h的jni头文件就需要这个.class文件,

使用javah command 格式如下:javah -jni -classpath xxx.class

注意路径指定到.class文件的包文件夹的上一层,例如要编译bin\classes\com\example\hellojni\HelloJni.class 文件,

需要cd 到classes\下就可

然后执行命令:

javah -jni -classpath . com.example.hellojni.HelloJni

会在classes\ 生成com_example_hellojni_HelloJni.h 文件

Ps: 有个‘.’在 -classpath 命令后。

code 如下:HelloJni.java

package com.example.hellojni;

import android.app.Activity;

import android.widget.TextView;

import android.os.Bundle;

public class HelloJni extends Activity

{

TextView tv ;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

tv = new TextView(this);

tv.setText( "get string from c: " + printHexString( getByteArray("2341")) );

setContentView(tv);

}

public native String stringFromJNI();

public native String[] getStringArray();

public native byte[] getByteArray(String userPin);

static {

System.loadLibrary("hello-jni");

}

}

编译后自动生成HelloJni.h,

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class com_example_hellojni_HelloJni */

#ifndef _Included_com_example_hellojni_HelloJni

#define _Included_com_example_hellojni_HelloJni

#ifdef __cplusplus

extern "C" {

#endif

/*

* Class: com_example_hellojni_HelloJni

* Method: stringFromJNI

* Signature: ()Ljava/lang/String;

*/

JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI

(JNIEnv *, jobject);

/*

* Class: com_example_hellojni_HelloJni

* Method: getStringArray

* Signature: ()[Ljava/lang/String;

*/

JNIEXPORT jobjectArray JNICALL Java_com_example_hellojni_HelloJni_getStringArray

(JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif

然后在.cpp中实现具体的函数功能:

#include <com_example_hellojni_HelloJni.h>

#include <stdio.h>

#include <string.h>

JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI

(JNIEnv *env, jobject thiz)

{

return (*env)->NewStringUTF(env,"the log of android is mad");

}

JNIEXPORT jbyteArray JNICALL Java_com_example_hellojni_HelloJni_getByteArray

(JNIEnv *env, jobject thiz, jstring jstr)

{

char const *bStr = NULL;

// jstring 2 char*

bStr = (*env)->GetStringUTFChars(env,jstr, 0);

jbyteArray RtnArr = NULL;

RtnArr = (*env)->NewByteArray(env,strlen(bStr));

(*env)->SetByteArrayRegion(env,RtnArr, 0, strlen(bStr), (jbyte*)bStr);

// if(bStr)

// {

// free(bStr);

// }

return RtnArr;

}

完成之后就可以编译了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐